To achieve lazy loading of data in your Inertia.js application, you should use an API endpoint to fetch the data after the initial component has been rendered. This approach allows you to first render the Home component and then load the data asynchronously using Axios.
Here is a step-by-step solution:
-
Create an API endpoint in Laravel to fetch the data:
In your
web.phporapi.phproutes file, define a route that returns the data you need:Route::get('/api/home-data', [HomeController::class, 'getData']);In your
HomeController, create thegetDatamethod:namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { public function getData() { // Perform your data calculation here $data = [ // Your data here ]; return response()->json($data); } } -
Render the Home component without the data initially:
In your route that renders the Home component, do not pass the data initially:
use Inertia\Inertia; Route::get('/home', function () { return Inertia::render('Home'); }); -
Fetch the data in the Home component using Axios:
In your
Home.vuecomponent, use themountedlifecycle hook to fetch the data after the component has been rendered:<template> <div> <h1>Home</h1> <div v-if="loading">Loading...</div> <div v-else> <!-- Render your grid with the data here --> <Grid :data="data" /> </div> </div> </template> <script> import axios from 'axios'; import Grid from './Grid.vue'; export default { components: { Grid }, data() { return { data: null, loading: true }; }, mounted() { axios.get('/api/home-data') .then(response => { this.data = response.data; this.loading = false; }) .catch(error => { console.error('Error fetching data:', error); this.loading = false; }); } }; </script>
In this solution, the Home component is rendered first, and then the data is fetched asynchronously using Axios. The loading state is used to show a loading indicator while the data is being fetched. Once the data is received, it is passed to the Grid component for rendering. This approach ensures that the initial render is fast and the data is loaded lazily.