Here is the code for react reducer. When I update data, the state becomes "undefined".
const intialState = { data: JSON.parse(localStorage.getItem('formData')) || [] };
const formReducer = (state = intialState, action) => {
switch (action.type) {
case 'ADD_DATA':
return { ...state, data: [...state.data, action.payload] };
case 'UPDATE_DATA':
{
console.log('form update data dispatch', action.payload);
const { id, data } = action.payload;
const newData = state.data;
newData.map((item, index) => {
if (item[0].uid == id) {
alert(item[0].uid === id);
newData[index] = data;
return (state.data = newData);
}
});
}
break;
default:
return state;
}
};
export default formReducer;
I am using useSelector()
to get updated data.
2
Answers
In the
UPDATE_DATA
case, you are not returning the updated state. This is causing the state to becomeundefined
. Thereturn
statement inside themap
callback returns the item in the array, and not the state.You can rewrite that case like this:
There are a couple issues in the
UPDATE_DATA
reducer case:Array.prototype.map
returns an array and its callback should be a pure function, it shouldn’t be used to mutate an external reference or the array it is iterating over.newData
is a reference to the currentstate.data
so the reducer case is also mutating the current state instead of returning a new state/array reference.A more correct implementation should look like the following:
or a bit more succinctly: