Mad
Mad

Reputation: 63

RTK query - how to refetch query during execution (race condition)

I use RTK query from redux-toolkit. I'm trying to solve race condition and I cannot find a built-in solution to refetch/cancel query while it is executing. I have 1 query (useSomeQuery()) and 1 mutation (useSomeMutation()). After mutation is done, query cache should be invalidated. To give some insight - user is changing form and by changing specific inputs (mutation) summary info is refreshed automatically.

Simple scenario that works:

  1. Mutation is done (I use invalidatesTags to invalidate cache).
  2. Query is automatically refetched.

Race condition scenario that doesn't work:

  1. Mutation is done.
  2. Query has started automatically to fetch data again (in progress).
  3. Second mutation has started and finished before step no. 2 is completed.
  4. Actual: the query has completed but is out of date according to my requirements, but RTK treats it as valid data. Expected: query is refetched.

I've tried to use api.util.getRunningOperationPromise() inside mutation using onQueryStarted to abort() but it seems that it only returns promise for the first load (not for updates).

Is there any built-in solution for that scenario?

Upvotes: 2

Views: 2657

Answers (1)

phry
phry

Reputation: 44276

At the moment, there is no good solution for this. Cancelling running queries was considered in the beginning, but could also lead to infinite loops etc., so the safest option was chosen for now.

If you have the drive to look further into this and maybe come up with an alternative solution, please open an issue on github :)

Upvotes: 0

Related Questions