Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React query: invalidate multiple queries but wait until they all finished on mutation success

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?

like image 265
nick Avatar asked Nov 26 '25 00:11

nick


1 Answers

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])
])
like image 198
TkDodo Avatar answered Nov 28 '25 13:11

TkDodo