Fetching Data on Route Change with React Query
Demonstrate how to fetch data with React Query based on the current route using React Router's 'useParams' hook to dynamically adjust the query.
import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';
Firstly, import useQuery from react-query and useParams from react-router-dom to use them in the component.
async function fetchData(id) {
const response = await fetch(`https://api.example.com/data/${id}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
}
Define an fetchData function that takes an id and fetches data from an API endpoint. It throws an error if the response is not ok.
function MyComponent() {
const { id } = useParams(); // Get the current route's id param
const { data, isLoading, error } = useQuery(['data', id], () => fetchData(id), { enabled: !!id });
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>{JSON.stringify(data)}</div>
);
}
Use the useQuery hook within our MyComponent to fetch data when the id parameter changes. The query is enabled only when id is truthy. Displays loading state, error messages, and the fetched data.