Using onError Callback for Global Error Handling
Illustrate the use of React Query's global onError callback to catch and handle errors uniformly across all queries, including logging errors for monitoring.
import { QueryClient, QueryClientProvider } from 'react-query';
// Create a client instance
const queryClient = new QueryClient({
defaultOptions: {
queries: {
onError: (error) => {
// Log every error
console.error('Global query error:', error);
// Here you can also send error to your error monitoring service
}
}
}
});
// Provide the client to your application
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your application's components go here */}
</QueryClientProvider>
);
}
This code snippet demonstrates the creation of a React Query client with a global onError callback. This callback is triggered whenever any query encounters an error, allowing for uniform error handling across the application, including error logging for monitoring purposes. The 'queryClient' is then passed to the 'QueryClientProvider' to make it available throughout the application.