reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.72k stars 1.17k forks source link

How to integrate optimistic updates with debounce in RTK Query? #2590

Open eelior opened 2 years ago

eelior commented 2 years ago

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()
        }
      },
...
phryneas commented 2 years ago

If there is no request happening, it's not really an "optimistic update" - you just want to change a cache value. Since there is no request going on, you'll have to do that outside the endpoint lifecycle. See General Updates