Request cancellation / prioritization #1116
Replies: 1 comment 1 reply
-
Thanks for the details, and the beautiful diagram! My suggestion is to do the following when you want to do an optimistic update: mutate(localState, false) // update local state
mutate(async () => {
await sendTheRequest() // update server state
return localState
}) The reason of the second If the mutate(localState, false)
mutate(async () => {
try {
const newServerState = await sendTheRequest()
return newServerState // might differ from `localState`
} catch (err) {
return oldState // request failed, fallback to the previous state!
}
}) Also make sure you are using the latest version of SWR, or the beta version |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Scenario
I have a query that looks something like this:
I use this data in order to show how far a song has been played (I'm using the Spotify API, proxied through Next.js API routes).
Now, I also have manual controls, for playing/pausing/volume etc. These execute a mutation to their according API routes (
/api/play
,/api/pause
, etc.). I also do a optimistic update on these (/api/player
) before I run the actual request, in order to faster update the UI.Problem
If a user clicks on the play/pause button, it sometimes get reverted to its previous state, if a refresh started on in the same interval as the user clicked the button.
Here's a demo of the issue occurring. (On the second tap you will see the pause/play button jump back to its previous position, until it gets back to the correct one again):
CleanShot.2021-04-08.at.08.26.36.mp4
Here's a very simple illustration of what happens:
Beta Was this translation helpful? Give feedback.
All reactions