Search code examples
redux-toolkitrtk-query

Update other slice after request


using RTK Query, how can one use the fetching functionality to update another the state of another slice?

Essentially I'm trying to keep all related-state next to each other, and thus after querying data with the useLazyGetQuery, I'd like to use the result and store it in an existing slices state.

Whilst something like the below works from an component, it makes the whole code messy

  const [trigger, result, lastArg] = useLazyGetFiltersQuery();

  React.useEffect(() => {
    if (result.status === 'fulfilled' && result.isSuccess === true && result.isLoading === false) {
      dispatch(updateData(result.data.map((pg) => ({ label: pg, value: pg }))));
    }
  }, [dispatch, result, result.isLoading, result.isSuccess, result.status]);

I'd rather want to setup some logic directly in the createApi method so that the resulting data is stored from the beginning in the slice I want.

Thanks


Solution

  • Generally, I would advise against copying data out of RTK-Query unless you have a very good reason: you will have to hand-write a lot of stuff, pretty much defeating the purpose of RTK-Query and you lose stuff like automatic cache collection of unused cache entries - from that point on you have to do that yourself.
    Also, that data is already in Redux. Usually, you should not duplicate data in the store when you can avoid it.

    That said, of course you can do it. For example, it is shown in the "Using extraReducers" authentication example:

    const slice = createSlice({
      name: 'auth',
      initialState: { user: null, token: null } as AuthState,
      reducers: {},
      extraReducers: (builder) => {
        builder.addMatcher(
          api.endpoints.login.matchFulfilled,
          (state, { payload }) => {
            state.token = payload.token
            state.user = payload.user
          }
        )
      },
    })
    

    Keep in mind: this is Redux and everything happens via actions. You will never have to useEffect something to write it back into state. Just listen for the right actions in your reducers.