So I’m using React query and I have a mutation and I have a onSucess callback like this:
onSuccess: () => {
return queryClient.invalidateQueries([FETCH_USER, userId]);
}
I want to invalidate another query, I know I can do this:
onSuccess: () => {
queryClient.invalidateQueries([FETCH_USER, userId]);
queryClient.invalidateQueries([FETCH_USER_BOOKS, userId]);
}
But if I don’t use the return then it doesn’t wait for the invalidation and sets the mutation as done.
Is there a way to use the return for both invalidations?
ideally, you would structure your query keys so that you can tackle them all in one invalidation:
[FETCH_USER, userId]
[FETCH_USER, userId, BOOKS]
then, you can target them with:
queryClient.invalidateQueries([FETCH_USER, userId])
this will fuzzily match all array keys that start have FETCH_USER at the first index and userId at the second, no matter what comes after them. That's why query keys should form a hierarchy if possible. I'm going into details here: https://tkdodo.eu/blog/effective-react-query-keys
if that is not possible, you can always wrap both promises in a Promise.all and return that:
onSuccess: () => Promise.all([
queryClient.invalidateQueries([FETCH_USER, userId]),
queryClient.invalidateQueries([FETCH_USER_BOOKS, userId])
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With