Blog>
Snippets

Resetting Errors with QueryErrorResetBoundary

Showcase how to programmatically reset errors within a component encapsulated by QueryErrorResetBoundary, using a button to retry the data fetching operation.
import { useQueryErrorResetBoundary } from 'react-query';
import { ErrorBoundary } from 'react-error-boundary';

function ErrorFallback({ error, resetErrorBoundary }) {
  return (
    <div role="alert">
      <p>An error occurred:</p>
      <pre>{error.message}</pre>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}
This piece of code imports necessary dependencies and defines an ErrorFallback component. It receives an error and a resetErrorBoundary function as props. The component renders the error message and includes a button to reset the error boundary.
function MyComponent() {
  const { reset } = useQueryErrorResetBoundary();

  return (
    <ErrorBoundary
      onReset={reset}
      fallbackRender={ErrorFallback}
    >
      {/* Your component logic here */}
    </ErrorBoundary>
  );
}
Here, the MyComponent function component utilizes useQueryErrorResetBoundary to access the reset function for resetting the query error state. It then uses the ErrorBoundary component from react-error-boundary, specifying the reset function to call on reset and the ErrorFallback component to render if an error occurs.