Basic Integration of QueryErrorResetBoundary
Demonstrate how to wrap components with QueryErrorResetBoundary and use the useQuery hook for fetching data, including basic error handling.
import { useQuery, QueryClient, QueryClientProvider } from 'react-query';
import { QueryErrorResetBoundary } from 'react-query';
import { ErrorBoundary } from 'react-error-boundary';
import React from 'react';
const queryClient = new QueryClient();
function MyComponent() {
const { data, error, isError } = useQuery('todos', fetchTodos);
if (isError) throw error;
return (<div>{data.map(todo => <p key={todo.id}>{todo.title}</p>)}</div>);
}
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div>
<p>An error occurred: {error.message}</p>
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
);
}
This code sets up a basic React component that uses `useQuery` from `react-query` to fetch some data and display it. If an error occurs during data fetching, the error is thrown, making use of React's error boundary to handle and provide UI for retrying.
function App() {
return (
<QueryClientProvider client={queryClient}>
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={reset}
>
<MyComponent />
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
</QueryClientProvider>
);
}
This is how you integrate the `QueryErrorResetBoundary` and `ErrorBoundary` with `MyComponent`. `QueryErrorResetBoundary` is utilized to provide a `reset` function that's passed to `ErrorBoundary` `onReset`, allowing the recovery mechanism to reset the state of queries in case of an error.