How can I delet a single element from the array in redux state using redux toolkit

2.3k views Asked by At

I am adding and deleting items in an array using the createSlice() function from the redux-toolkit library.

The addProject reducer function works fine but the removeRpoject doesn't work.

//projects.js

import { createSlice } from "@reduxjs/toolkit";

let lastId = 0;

const slice = createSlice({
  name: "projects",
  initialState: [],
  reducers: {
    projectAdded: (projects, action) => {
      projects.push({
        id: ++lastId,
        name: action.payload.name,
      });
    },
    projectRemoved: (projects, action) =>
      (projects = projects.filter((pro) => pro.id !== action.payload.id)),
  },
});
export const { projectAdded, projectRemoved } = slice.actions;
export default slice.reducer;

//store.js

import { configureStore } from "@reduxjs/toolkit";
import reducer from "./projects";
const store = configureStore({ reducer: reducer });

export default store;

//index.js

import store from "./store/store";
import { projectAdded, projectRemoved } from "./store/projects";
const unsubscribe = store.subscribe(() => {
  console.log("store Changed", store.getState());
});
store.dispatch(projectAdded({ name: "Project 1" }));
store.dispatch(projectRemoved({ id: 1 }));

1

There are 1 answers

0
Johannes Reuter On BEST ANSWER

You are replacing the root object of your state (projects) - this kills the immer change detection.

The simplest way is to just return the filtered array without assigning it to the draft object first:

projectRemoved: (projects, action) => projects.filter((pro) => pro.id !== action.payload.id),

See also: https://immerjs.github.io/immer/docs/update-patterns#array-mutations