Replies: 1 comment 3 replies
-
The designated way to do optimistic UI would be to use This is very similar to what you're saying about the two relevant signals, in this case. I recognize the theoretical possibility of the race condition. However, I don't think it's actually possible; because of the synchronous and single-threaded nature of JavaScript/the browser's event loop, and the synchronous nature of the reactive system, I'm pretty sure it's not possible for an async event to arrive and be processed between the moment a signal updates and the moment that update is reflected in the DOM. Either the event from the server arrives before the user clicks the button, in which case the user-button-clicked version wins, which is correct; or the event from the server arrives after the user clicks the button, in which case the server version wins, which is correct. I don't believe it's possible for the server-sent event to arrive and be processed between the button click and the DOM update. |
Beta Was this translation helpful? Give feedback.
-
In the
counter_isomorphic
example (multi-user-mode), all clients see exactly the same counter, synchronized through SSE. In that way however, updating the count might be slow due to server latency. Suppose we want to improve the example by making the UI optimistic: Each time we send a count update request to the server, we immediately want to update our own counter. When we receive feedback through SSE, we want to update the counter again (the server being the single source of truth).What is the proper way to do this in Leptos?
Some thoughts:
There are two relevant read signals for count in this case: One is given by the SSE, the other is given by the input signal of the server action (not exactly true in the example, but can be easily refactored in that way). A quick and dirty solution might be to create a third count signal and two effects such that each change to one of the former signals updates the third. But now we have a potential race condition: If the server communication is faster than the client updating itself for some reason, the client might override a recent server event with its outdated update request (violating the single source of truth principle).
A robust solution should be possible by enumerating all events, so that both signals contain the current count, and the corresponding event number. Now the third signal could just be a derived signal choosing the count value with higher event number (server signal wins on equality). However, this solution seems nontrivial and clumsy. Am I missing an elegant solution?
Beta Was this translation helpful? Give feedback.
All reactions