I implemented optimistic updates successfully, but couldn't figure out how to use debounce in the process.
Take for example just a text input: I want the UI to change immediately, but I don't want to make a post request for each letter typed. I want to wait until the typing is done and then make the request.
For example. Lets say I use useSetMsg
hook in some component:
...
const SystemMessages: React.FC = () => {
const [setMsg] = useSetMsg();
...
If I wrap setMsg
with some debounce logic, my optimistic update will be also debounce resulting in losing my UI responsiveness.
So I need to implement that logic in the onQueryStarted
method I use for the optimistic updates but I'm not sure how.
...
async onQueryStarted({ sub, token, msg }, { dispatch, queryFulfilled }) {
const patchResult = dispatch(
injectedRtkApi.util.updateQueryData('getMsg', { sub, token }, (draft) => {
draft = msg
return draft;
})
)
try {
await queryFulfilled
} catch {
patchResult.undo()
}
},
...