Modular Slice Creation with createReducer
Explain how to construct a modular user slice that can manage real-time user session data with `createReducer` for better scalability.
import { createAction, createReducer } from '@reduxjs/toolkit';
// Action creators
export const userLoggedIn = createAction('user/loggedIn');
export const userLoggedOut = createAction('user/loggedOut');
export const userSessionUpdated = createAction('user/sessionUpdated');
// Initial state
const initialState = {
currentUser: null,
sessionData: {},
isLoggedIn: false
};
// Modular user slice reducer created with createReducer
export const userReducer = createReducer(initialState, (builder) => {
builder
.addCase(userLoggedIn, (state, action) => {
state.currentUser = action.payload;
state.isLoggedIn = true;
})
.addCase(userLoggedOut, (state) => {
state.currentUser = null;
state.sessionData = {};
state.isLoggedIn = false;
})
.addCase(userSessionUpdated, (state, action) => {
state.sessionData = { ...state.sessionData, ...action.payload };
});
});
Defines actions and a reducer for a user slice managing user sessions using createReducer for enhanced modularity and scalability. The reducer updates state for user login, logout, and session data updates.