Reputation: 180
I need to data from one array to another in my Context state and I chose to do so using useReducer()
. This is how that action looks
case 'ADD_CATEGORY':{
if(state.catList.length>0){
let nextState = { ...state };
let catList = state.catList.filter(c => c.localeCompare(state.category)!==0);
let categories = state.categories;
categories.push (state.category);
nextState.categories = categories;
nextState.catList = catList;
console.log(state.category);
return nextState
}else return state;
}
This is how the state looks
const initialState = {
towns:[],
name: '',
parish: '',
category: '',
townsToSubmit: [],
categories:[],
catList:[],
}
According to this github issue I'm supposed to expect useReducer() to call twice if I'm reading the thread correctly since the react app is using strict mode and its to see if my code causes side effects. How do I do that when adding to an array.
The main issue that this causes is that my arrays end up having elements repeated because they're always added twice. Since StrictMode is supposed to help detect side effects is their a better way of adding data to an array?
Upvotes: 1
Views: 458
Reputation: 101768
As the creators of Redux stress over and over, your reducers need to be pure. { ...state }
creates a shallow copy of state
, so if you modify the values of any reference types in the state (e.g. by using .push()
on an array), that change will happen in both the previous version of the state and the next. If the same modification is repeated twice on account of strict mode, then this means you have a problem.
So use only pure operations:
case 'ADD_CATEGORY':{
if(state.catList.length > 0) {
return {
...state,
catList: state.catList.filter(c => c.localeCompare(state.category) !== 0),
categories: [...state.categories, state.category],
};
}
return state;
}
Upvotes: 2