T
TanStack6mo ago
ratty-blush

Reset Mutation State in onError Handler of MutationCache

Hello, guys! It’s possible to reset the mutation state inside the global onError handler for MutationCache? I want to catch an AuthExpiredError from my API (when the user’s session has expired), in order to reset the state of all active queries and mutations, and then show a login modal. Something like this:
{
queryClient: new QueryClient({
queryCache: new QueryCache({
onError(error, query) {
if (error instanceof AuthExpiredError) {
query.reset();
displayLogInForm();
}
},
}),
mutationCache: new MutationCache({
onError(error, variables, context, mutation) {
if (error instanceof AuthExpiredError) {
mutation.reset(); /// how to reset mutation state? 🤔
displayLogInForm();
}
},
}),
}),
}
{
queryClient: new QueryClient({
queryCache: new QueryCache({
onError(error, query) {
if (error instanceof AuthExpiredError) {
query.reset();
displayLogInForm();
}
},
}),
mutationCache: new MutationCache({
onError(error, variables, context, mutation) {
if (error instanceof AuthExpiredError) {
mutation.reset(); /// how to reset mutation state? 🤔
displayLogInForm();
}
},
}),
}),
}
1 Reply
suitable-rose
suitable-rose6mo ago
I can't directly answer your question - someone else may know the answer to this. With this said, in my companies case, we did this at an API level rather than a tanstack level. In our axios interceptor, we simply caught expired auth responses, and cleared the entire cache- since we don't want to risk any authenticated data staying in the cache if they are no longer authenticated. Literally just a matter of calling queryClient.clear() in our middleware whenever we get a session expired message. Personally, I recommend this over just clearing the individual query or mutation, since it's very possible that someone could have cached a lot of sensitive data and then their session is expired... you do not want that cache sticking around across sessions.

Did you find this page helpful?