-
Hi! I'm trying to implement an input field that would "flush" its value to the backend as soon as possible. The server I'm working with is sluggish and responds with random delays. It also returns errors from time to time, but I'll leave that out of scope. First, the naive approach: Well, that's expected, let's move on to the optimistic updates. I did it by the book: added |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I think your code looks fine, and there isn't much react-query (or the frontend in general) can do here (except debounce the mutations maybe): queries can be cancelled to not override outgoing mutations, but if you fire off two mutations at the same time, I think it's the server's responsibility to handle concurrent modifications (ignore them or queue them). In your example, given a
The So technically, the latest value is then |
Beta Was this translation helpful? Give feedback.
-
While I agree some of this is the responsibility of the server, I think the developer experience of writing synced state could be improved. @TkDodo I was inspired by your blog post which separated the data into a draft/server state. I put together a hook which can be used to automatically poll data from the server and post data to the server when the data has changed. In the demo I have the same "form" replicated twice on the page which shows how local state can be displayed in multiple places, and if you open up a second browser tab you can see that the state is synced to a server. The implementation for the hook is in The hook does rely on zustand but I Hope this helps other people trying to implement this type of functionality in the future! |
Beta Was this translation helpful? Give feedback.
I think your code looks fine, and there isn't much react-query (or the frontend in general) can do here (except debounce the mutations maybe): queries can be cancelled to not override outgoing mutations, but if you fire off two mutations at the same time, I think it's the server's responsibility to handle concurrent modifications (ignore them or queue them).
In your example, given a
serverState
of"a"
, I typed"b"
and then"c"
and got the following log output (I also added the values to the logs):