redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

Invalidating a request mid-flight

Open hornta opened this issue 2 years ago • 10 comments

I have a need to invalidate a query request that is in mid-flight. At least that's what I believe I want to do but I will explain my use case.

So in our UI we have a simple checkbox/switch that a user can toggle on/off, essentially just toggling a boolean flag in a data model. We got a toggle mutation endpoint for this in which I've implemented the onQueryStarted to manually toggle the flag in our query endpoints(we got several endpoints for this data model but it doesn't matter).

Everything works good so far, there is no UI-delay what so ever, yay optimistic updates!!! :-)

However there is a problem when the user flicks the switch on/off in rapid succession. This triggers two mutations to our api, essentiallt taking out itself since it's just a flag that toggles from false -> true -> false. This is fine. But for the first flick(false -> true) the query endpoints gets invalidated and starts to refetch the data model since it's stale.

For the second flick (true -> false) we once more trigger a mutation to set the data model in the backend to false. The query endpoints hasn't responded yet but whatever they will return I consider it stale because I've mutated the data model AFTER the query endpoint fired.

This ends up in a weird state where the cached response in RTK differs from the state in my backend.

What are some solutions to this?

  • I think it would be nice for RTK to abort the query and start a new one.
  • Or make RTK at least refetch the invalidated queries once again. This might be ugly because RTK doesn't see them as stale.

I was thinking of a way to "force invalidate" tags to tell RTK that even though it has mid-flight requests, they are stale. invalidateTags: [{ type: "Item", id: arg.id, forceInvalidate:true }]

Relates to: https://github.com/reduxjs/redux-toolkit/issues/2444

RED-12

hornta avatar Jun 23 '22 13:06 hornta