reduxjs / redux-toolkit

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

Use reducer inside updateQueryData in RTK Query #3602

Closed alexeykurbako closed 1 year ago

alexeykurbako commented 1 year ago

Hey. I am playing around optimistic and pessimistic update strategies and faced with one little issue: I am forced to duplicate code from reducer inside of updateQueryData. Is it possible to use reducer from slice inside updateQueryData function to prevent code duplicating? This is my actual implementation:

      async onQueryStarted(queryArgs, { dispatch, queryFulfilled }) {
        const { data: newSlide } = await queryFulfilled;

        dispatch(
          baseCreateApi.util.updateQueryData('getSlideGroups', undefined, draft => {
            draft.push(newSlide)
          })
        )
      }

What I want to implement:

      async onQueryStarted(queryArgs, { dispatch, queryFulfilled }) {
        const { data: newSlide } = await queryFulfilled;

        dispatch(
          baseCreateApi.util.updateQueryData('getSlideGroups', undefined, draft => {
            createSlideGroup(newSlide);
          })
        )
      }

my reducer:

   createSlideGroup: (state, { payload }) => {
      state.push(payload)
    },
EskiMojo14 commented 1 year ago

i don't fully understand why you'd want to do this, but it is possible thanks to createSlice including its reducers under slice.caseReducers:

      async onQueryStarted(queryArgs, { dispatch, queryFulfilled }) {
        const { data: newSlide } = await queryFulfilled;

        dispatch(
          baseCreateApi.util.updateQueryData('getSlideGroups', undefined, draft => {
            mySlice.caseReducers.createSlideGroup(draft, mySlice.actions.createSlideGroup(newSlide));
          })
        )
      }

notice that you have to use the action creator too, since the case reducer expects an action.

on the other hand, it may be more desired to create a separate util function that both your slice reducer and updateQueryData call use.