0

Here is the example from the documentation. I'm looking to implement a updateUser action with redux thunk, but I want for it to remain under the same slice as users for example. How can this be achieved with one slice?

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'

// First, create the thunk
const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await userAPI.fetchById(userId)
    return response.data
  }
)

// Then, handle actions in your reducers:
const usersSlice = createSlice({
  name: 'users',
  initialState: { entities: [], loading: 'idle' },
  reducers: {
    // standard reducer logic, with auto-generated action types per reducer
  },
  extraReducers: {
    // Add reducers for additional action types here, and handle loading state as needed
    [fetchUserById.fulfilled]: (state, action) => {
      // Add user to the state array
      state.entities.push(action.payload)
    }
  }
})

// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))
Jacob Kelley
  • 395
  • 3
  • 13
  • thunk is a middleware, it doesn't decouple to a slice – Dennis Vash Jan 08 '21 at 16:03
  • @DennisVash Can you expand on that, please? How would I create an `userUpdate` action that sends the payload to a service while retaining the action to fetch a user as well? – Jacob Kelley Jan 08 '21 at 16:05
  • I suggest reading about how middleware works, either way, there are enough examples in docs and duplicate questions you can search for. – Dennis Vash Jan 08 '21 at 16:14

0 Answers0