简体   繁体   中英

Receiving state mutation error

In my react/redux application have the following actions

export function getSeatingChartConfiguration(team) {
 return function(dispatch) {
  ref.child(team.key).once('value').then(function(snapshot) {
    dispatch(loadSeatingChart(snapshot.val()));
  });
 };
}

export function saveSeatingChartSection(key, sectionData){
 return function(dispatch) {
  ref.child(key).once('value').then(function(snapshot) {
   let data = snapshot.val();
   let sections = data.sections;
   let index = snapshot.val().sections.map( (el) => el.name).indexOf(sectionData.name);
   if(index !== -1) {
    sections[index] = sectionData;
   } else {
    sections.push(sectionData);
   }
   data.sections = sections;
   ref.child(key).update(data, function(error) {
    dispatch(loadSeatingChart(data));
   });
  });
 };
}

Here is the reducer

export default function seatingChart(state = {}, action) {
 switch(action.type) {

  case actionTypes.LOAD_SEATING_CHART_CONFIGURATION:
   return action.seatingChartConfiguration;

  default:
   return state;
 }
}

I am not getting any errors when getSeatingChartConfiguration() is called but I have receiving Error: A state mutation was detected between dispatches, in the path seatingChart.sections.2.points . What do I need to change in my action or reducer to not mutate the state.

Use Object.assign with initial state to avoid state mutation like below,

const initialState = { seatingChartConfiguration: [] }

export default function seatingChart(state = initialState, action) {
 switch(action.type) {

  case actionTypes.LOAD_SEATING_CHART_CONFIGURATION:
   return Object.assign({}, state, { seatingChartConfiguration: action.seatingChartConfiguration });

  default:
   return state;
 }
}

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