Home >Web Front-end >JS Tutorial >State Management: Redux Toolkit React JS
Redux Toolkit simplifies global state management in React applications. In this article, we’ll explore how to implement an authentication system using Redux Toolkit, including store configuration, slices, and async actions with thunks.
1. Configuring the Redux Store
The Redux store is configured using configureStore. In app.tsx, we set up a global reducer, middleware, and enable developer tools for debugging.
import { lazy } from 'react'; import { createRoot } from 'react-dom/client'; import { Provider } from "react-redux"; import { combineReducers, configureStore } from '@reduxjs/toolkit'; import { rootReducer } from './slice'; import { setupAxios } from './_metronic/helpers/Axios'; import axios from 'axios'; import { thunk } from 'redux-thunk'; setupAxios(axios); const AppRoutes = lazy(() => import('./routers/AppRoutes')); const store = configureStore({ reducer: combineReducers({ masterState: rootReducer, }), middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(thunk), devTools: true, }); createRoot(document.getElementById('root')!).render( <Provider store={store}> <AppRoutes /> </Provider> );
2. Creating the Root Reducer
The root reducer manages global state by combining different slices. Here, we include an auth slice for authentication.
import { AuthReducer } from "#/modules/auth/store/auth.slice"; import { combineReducers } from "redux"; export const rootReducer = combineReducers({ Auth: AuthReducer, });
The Authslice handles authentication-specific state, which is defined using createSlice.
3. Defining the Authentication Slice
Using createSlice, we define the state structure, synchronous reducers, and extraReducers to handle async actions.
import { createSlice } from "@reduxjs/toolkit"; import { AuthState, initialAuthState } from "../model/authModel"; import { setLocalStorageData } from "#/_metronic/helpers/localstorage/accessToken"; import { AUTH_KEY, REFRESH_KEY } from "#/_metronic/helpers/env"; import { login } from "./auth.asyncAction"; const initialState: AuthState = initialAuthState; export const authSlice = createSlice({ name: "auth", initialState, reducers: {}, extraReducers: (builder) => { builder .addCase(login.pending, (state) => { state.loading = true; state.error = undefined; state.isSubmitting = true; }) .addCase(login.fulfilled, (state, action) => { const { payload }: any = action; if (payload?.status === 'Error') { state.error = payload?.message || payload; } else { state.success = true; state.isLogin = true; setLocalStorageData(AUTH_KEY, payload?.api_token); setLocalStorageData(REFRESH_KEY, payload?.refreshToken); } state.loading = false; state.isSubmitting = false; }) .addCase(login.rejected, (state, action) => { const { payload }: any = action; state.loading = false; state.error = payload?.data || payload; state.isSubmitting = false; }); }, }); export const { reducer: AuthReducer } = authSlice;
4. Creating Async Actions with createAsyncThunk
The login async action interacts with an API to handle user authentication.
import { createAsyncThunk } from "@reduxjs/toolkit"; import { doLogin } from "../api/auth_api"; export const login = createAsyncThunk('login', async (payload: any, { rejectWithValue }) => { try { return await doLogin(payload); } catch (error: any) { return rejectWithValue(error?.data || error); } });
The action calls the API and processes responses or errors with rejectWithValue.
5. Creating the Authentication API
The API layer uses Axios to communicate with the backend. Here's the implementation for the login request.
import axios from 'axios'; import { ILogin, UserModel } from '../model/authModel'; import { BASE_URL } from '#/_metronic/helpers/env'; export const AUTH_URL = `${BASE_URL}/auth`; export const doLogin = (payload: ILogin) => axios.post<UserModel>(AUTH_URL, payload);
With Redux Toolkit, managing global state becomes streamlined, especially for handling complex workflows like user authentication. By breaking the implementation into smaller modules (store, slice, and API), we ensure scalability and maintainability in our React applications.
The above is the detailed content of State Management: Redux Toolkit React JS. For more information, please follow other related articles on the PHP Chinese website!