Search code examples
reduxredux-toolkitredux-promise-middleware

How to use Redux Promise Middleware with slices in Redux Toolkit?


I'm using the slices feature of Redux Toolkit. As you may know, one slice returns an action for every created reducer.

I want to use the redux-promise-middleware library, which for a given ACTION_TYPE, it creates three possible new actions: ACTION_TYPE_FETCHING, ACTION_TYPE_FULFILLED, and ACTION_TYPE_REJECTED. How do I handle this from the point of view of the slices?


Solution

  • You'd need to add the expected action types to the extraReducers section of createSlice, like:

    // could use a predefined action constant if desired:
    const actionFetching = "ACTION_TYPE_FETCHING"
    
    const usersSlice = createSlice({
      name: "users",
      initialState,
      reducers: {
        // specific case reducers here
      },
      extraReducers: {
        // could use computed key syntax with a separate type constant
        [actionFetching ]: (state, action) => {}
        // or the actual field name directly matching the type string
        ACTION_TYPE_FULFILLED: (state, action) => {}
      }
    })