简体   繁体   中英

trying to remove all items and add incoming items from a nested redux object

I have below reducer and below initial State. classinfo is the parent state which has a nested state array of students. with the below reducer I am planning (replace previous students with new students ) to delete all students from the previous state, add new students from "action.data.students" and return a new state. first time I add students there is no issue, when I add another student I am getting the error "A state mutation was detected between dispatches" please let me know, where I am doing it wrong.

classInfo[ { Id:"", students:[] }]

function sampleReducer(state = initialState.classInfo, action) {
  switch (action.type) {
    case types.ADD_CLASSROOMS:
      return [...state, ...action.data];
    case types.REMOVE_CLASSROOMS:
      return state.filter((class) => class.id !== action.data);
    case types.ADD_STUDENT_DETAILS:
      const stateObj = state.map((class, i) => {
        if (class.id === action.data.id) {
          return {
            ...class,
            students: {
              ...action.data.students,
            },
          };
        }
        return {
          ...class,
        };


      });
      return stateObj;

    default:
      return state;
  }
}

You are spreading object for students . It's an array. So use square brackets and spread the students array - students: [...action.data.students]

...
case types.ADD_STUDENT_DETAILS:
      const stateObj = state.map((class, i) => {
        if (class.id === action.data.id) {
          return {
            ...class,
            students: [ //<----use square brackets(as its an array)
              ...action.data.students
            ],
          };
        }
        return class;


      });
      return stateObj;
    ...

You are doing great, do not to mutate the state simply means, do not alter the prevState just update the state.

The main error is that, you are trying to change state of student as previously it was array type and while you are updating it you made it as object type just a typo. please use [ ] instead of { }

 const state = { id: 1, students: [ {first: 1}, {second: 2}, {third: 3} ] } const action = { data: { students: [ {fourth: 4} ] } } const updatedStudents = {...action.data.students } console.log(state); console.log(updatedStudents);

So, in your case->

case types.ADD_STUDENT_DETAILS:
      const stateObj = state.map((class, i) => {
        if (class.id === action.data.id) {
          return {
            ...class,
            students: [
              ...action.data.students,
            ],
          };
        }
        return {
          ...class,
        };


      });
      return stateObj;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM