When working with the Redux-Toolkit (RTK) slice:
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
// Sets the user
setUser: (state, action: PayloadAction<string | null>) => {
state.user.email = action.payload;
},
setLoading: (state, action: PayloadAction<boolean>) => {
state.isLoading = action.payload;
},
},
});
and using these exports:
export const { setUser, setLoading } = userSlice.actions;
export default userSlice.reducer;
This RTK slice creates the following key exports:
- Generates
setUser
and setLoading
functions based on the declared reducer functions.
- A slice reducer function that is utilized in creating the store object or combined with other reducers to form a reducer tree when configuring the store, e.g.
configureStore
.
The purpose of action.payload
needs clarification. Why is it used here and what role does it play?
All Redux action functions produce an action object, typically containing a type
property. Actions generated by RTK include an additional payload
property within the action object. This action.payload
is referenced in the reducer functions.
For instance, dispatching the setUser
action from the UI.
dispatch(setUser("Drew"));
dispatch(setUser(null));
This triggers the setUser
action with either the string argument "Drew"
or null
, resulting in an action object
{ type: "user/setUser", payload: "Drew" }
or
{ type: "user/setUser", payload: null }
. The dispatched action is then processed by the
dispatch
function, akin to
dispatch({ type: "user/setUser", payload: "Drew" })
, before reaching the reducer tree.
The setReducer
function manages this specific "user/setUser"
action type and extracts the payload
property from the action object.
setUser: (state, action: PayloadAction<string | null>) => {
state.user.email = action.payload; // Either "Drew" or null
}
As a result, the value stored in state.user.email
is set to the received payload value "Drew"
.
Similarly, you can pass a boolean value when triggering the setLoading
action.
dispatch(setLoading(true));
setLoading: (state, action: PayloadAction<boolean>) => {
state.isLoading = action.payload; // true
},