DeveloperBreeze

Dynamic Reducer Loading Development Tutorials, Guides & Insights

Unlock 1+ expert-curated dynamic reducer loading tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your dynamic reducer loading skills on DeveloperBreeze.

Advanced State Management in React Using Redux Toolkit

Tutorial December 09, 2024
javascript

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

// Async action for fetching users
export const fetchUsers = createAsyncThunk(
  'users/fetchUsers',
  async (_, thunkAPI) => {
    try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/users');
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.message);
    }
  }
);

const usersSlice = createSlice({
  name: 'users',
  initialState: {
    entities: [],
    status: 'idle',
    error: null,
  },
  reducers: {
    addUser: (state, action) => {
      state.entities.push(action.payload);
    },
    updateUser: (state, action) => {
      const { id, changes } = action.payload;
      const existingUser = state.entities.find((user) => user.id === id);
      if (existingUser) {
        Object.assign(existingUser, changes);
      }
    },
    deleteUser: (state, action) => {
      state.entities = state.entities.filter((user) => user.id !== action.payload);
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUsers.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchUsers.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.entities = action.payload;
      })
      .addCase(fetchUsers.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload;
      });
  },
});

export const { addUser, updateUser, deleteUser } = usersSlice.actions;
export default usersSlice.reducer;
  • Reducers: Define actions to manipulate the state (addUser, updateUser, deleteUser).
  • Async Actions: Handle API calls with createAsyncThunk.
  • Extra Reducers: Manage different states (loading, succeeded, failed) based on async actions.