In this episode, we take a look at how to implement lazy data loading with Inertia.js. Normally, when you pass data from your controller to a template, that data is always available up front and immediately accessible in your components. But sometimes, you don't want all your data to be loaded right away — maybe you want to load extra data only when a user requests it. That's where lazy loading comes in.
We start by checking out the Inertia docs and exploring the three main options for data evaluation. The first is how we've been doing things so far: passing data directly, so it's always available. But then we dive into wrapping data in a function, which allows Inertia to only evaluate and fetch that data when it's actually needed. Finally, we focus on the Inertia::lazy()
method, which is perfect for loading data like comments or posts only in response to a user action.
To demonstrate this, we build a button on the user's profile page that, when clicked, loads the user's posts via a lazy request. We go through setting up the controller to send the data lazily, wiring up the front-end button to make a partial AJAX request using the router, and making sure the fresh data loads in just when we need it.
Along the way, we hit a quick snag with making sure we pass the correct user data, but we solve that and confirm that hitting the button brings in our data on-demand. By the end of this lesson, you'll know exactly how to keep your initial page loads lean, and let users fetch additional data only when they need it!