redux toolkit also has slices, which combines createAction and createReducer.
So it automatically creates actions and reducers for us.
questions.js
let’s import createSlice
1 |
import { createSlice } from '@reduxjs/toolkit'; |
createSlice takes an object with properties name, initialState, and reducers.
name represent the feature of this reducer.
intialState is the starting point of the state.
Finally, we have a reducers property, which references an object. Inside this object,
1 2 3 4 5 6 7 8 9 10 |
createSlice({ name: 'questions', initialState: [], reducers: { // actions => actionHandlers questionAdded: { // } } }) |
In the previous approach, questionAdded was an object, so we can use [questionAdded] to check for the type.
In this approach, questionAdded is just a property. Slices automatically creates actionTypes and actions for us.
let’s look at this slice object.
1 2 |
const slice = createSlice({...}); console.log(slice); |
We see the properties. We need to default export the reducer and export the actions.
So with this implementation we can remove the previous actions and reducers.
1 |
export default slice.reducer; |
also need to export actions. We do so by extracting actions from slice.actions
1 |
export const { questionAdded, questionAnswer } = slice.actions; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
let lastId = 0; const slice = createSlice({ name: 'questions', initialState: [], reducers: { // actions => action handlers questionAdded: (state, action) => { state.push({ id: ++lastId, description: action.payload.description, answer: action.payload.answer }); }, questionAnswer: (state, action) => { const index = state.findIndex(question => question.id === action.payload.id); state[index].answer = action.payload.answer; } } }); export const { questionAdded, questionAnswer } = slice.actions; export default slice.reducer; |