Error Handling with React Query
Example of handling errors in React Query when data fetching fails, including displaying user-friendly error messages.
import { useQuery } from 'react-query';
function fetchTodo() {
return fetch('https://jsonplaceholder.typicode.com/todos/1').then(res =>
res.ok ? res.json() : Promise.reject('Failed to fetch')
);
}
Defines a fetch function that fetches data from an API. It checks if the response is ok, otherwise rejects the promise with an error message.
function TodoComponent() {
const { data, error, isLoading } = useQuery('todo', fetchTodo);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error occurred: {error.message}</div>;
return <div>{data.title}</div>;
}
Uses the useQuery hook from React Query to fetch data using the fetchTodo function. It renders different components based on the loading state and presence of an error.