Handling Hydration Errors in React Query
Demonstrate error handling during the hydration process in a React Query application. Show how to catch and handle errors when dehydrating and rehydrating state, ensuring the application remains robust and user-friendly.
import { QueryClient, QueryClientProvider, Hydrate } from 'react-query';
import { useState } from 'react';
function MyApp({ Component, pageProps }) {
const [queryClient] = useState(() => new QueryClient());
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={pageProps.dehydratedState}>
<Component {...pageProps} />
</Hydrate>
</QueryClientProvider>
);
}
This piece initializes React Query with a QueryClient and wraps the app component inside QueryClientProvider and Hydrate components, allowing for dehydrated state to be rehydrated.
import { useQuery, useQueryClient } from 'react-query';
function fetchUserData() {
// Fetch user data from an API
}
function UserProfile() {
const queryClient = useQueryClient();
const { data, error, isLoading } = useQuery('user', fetchUserData, {
// Handle rehydration error
onError: (err) => {
console.error('Failed to rehydrate user query:', err);
// Attempt to refetch or handle the error appropriately
queryClient.invalidateQueries('user');
}
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error occurred: {error.message}</div>;
return <div>{data.name}</div>; // Render user data
}
Uses useQuery to fetch user data and handle errors during rehydration. If an error occurs (e.g., mismatched state), it invalidates the query causing a refetch, ensuring data consistency.