-
Hello. I'm using a great library. I would like to use queryCache, mutationsCache options in queryClient to handle errors globally. Here, the handler function provided by the onError method is simply to display the snackbar. However, the context manages the snackbar so that it can be used anywhere. The code I tried for the first time is as follows. const queryClient = (errorHandler: (error: any, cb?: () => void) => void) =>
new QueryClient({
mutationCache: new MutationCache({
onError: (err, variables, context, mutation) => {
if (mutation.meta?.shouldBeHandledByGlobalErrorHandler) {
errorHandler(err);
}
},
}),
queryCache: new QueryCache({
onError: (err, query) => {
if (query?.meta?.shouldBeHandledByGlobalErrorHandler) {
errorHandler(err);
}
},
}),
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
},
},
});
export const ErrorContext = createContext<{
handleError: (error: any, cb?: () => void) => void;
}>({
handleError: () => {}, // eslint-disable-line @typescript-eslint/no-empty-function
});
const ErrorContextProvider: FC<{}> = ({ children }) => {
const navigate = useNavigate();
const handleAxiosError = (error, cb?: () => void) => {
// open snackbar
};
const contextValue = {
handleError: useCallback((err, cb) => handleAxiosError(err, cb), [])
};
return (
<ErrorContext.Provider value={contextValue}>
<QueryClientProvider client={queryClient(handleAxiosError)}>{children}</QueryClientProvider>
</ErrorContext.Provider>
);
}; The validateQueries function does not seem to work properly when using the above code. The reason for this is that we are using useNavigate hooks inside the context component, and the queryClient also has a problem as the component is re-rendering. I think the solution is to wrap the QueryClientProvide in App.tsx and specify the handler to use in queryCache, muteCache onError. If you can use it in any other way, I would appreciate it if you could let me know. I need your help. Please help me. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
what you need to do is make the queryClient stable, when you create it inside a react component. You can do this with refs or with state (not with useMemo). I've blogged about this here: https://tkdodo.eu/blog/use-state-for-one-time-initializations I prefer using state:
inside the query client creation, you can closure over |
Beta Was this translation helpful? Give feedback.
what you need to do is make the queryClient stable, when you create it inside a react component. You can do this with refs or with state (not with useMemo). I've blogged about this here: https://tkdodo.eu/blog/use-state-for-one-time-initializations
I prefer using state:
inside the query client creation, you can closure over
snackbar
. You can also extract that to an external function, doesn't really matter.