Adding Tanstack react-query to laravel 11 reactjs inertia project
To add Tanstack's react-query library to a Laravel 11 project that uses ReactJS and Inertia for building the frontend, follow these steps:
- Install react-query: First, you need to install react-query in your Laravel project. Navigate to your project's root directory in your terminal and run:
npm install react-query
Or if you prefer using Yarn:
yarn add react-query
- Import react-query in your JavaScript entry file:
Open the
app.js
file located in theresources/js
directory and import react-query at the beginning of the file:
import 'react-query/reset';
import React from 'react';
import ReactDOM from 'react-dom';
import { createInertiaApp } from '@inertiajs/inertia';
import { QueryClient, QueryClientProvider } from 'react-query';
import { InertiaProgress } from '@inertiajs/progress';
import App from './App.vue';
const queryClient = new QueryClient();
createInertiaApp({
queryClient: queryClient,
progress: InertiaProgress,
root: document.getElementById('app'),
});
ReactDOM.render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>,
document.getElementById('app')
);
- Create a new React component to use react-query:
Create a new React component file, for example,
FetchData.js
, inside theresources/js/components
directory:
import React from 'react';
import { useQuery } from 'react-query';
const FetchData = () => {
const { data, error, isLoading } = useQuery('todos', async () => {
const res = await fetch('/api/todos');
return res.json();
});
if (isLoading) return 'Loading...';
if (error) return 'An error has occurred: ' + error.message;
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
};
export default FetchData;
Replace /api/todos
with the correct API route for your Laravel project.
- Use the new component in your Inertia view:
Create a new Inertia view file, for example,
welcome.blade.php
, inside theresources/views
directory:
<template>
<div class="welcome">
<h1 class="text-2xl font-bold text-gray-800">
Welcome to Laravel!
</h1>
<FetchData />
</div>
</template>
<script>
import FetchData from '@/Components/FetchData';
export default {
components: {
FetchData,
},
};
</script>
- Update your routes:
Update the
routes/web.php
file to include the new route for the component:
Route::get('/', function () {
return Inertia::render('Welcome');
});
Now, when you visit the homepage of your Laravel application, react-query will fetch the data from your Laravel API using Inertia and display it in the FetchData
component.