Search code examples
reactjsreduxreact-redux

State becomes undefined while calling 'UPDATE_DATA' action from redux


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.


Solution

  • In the UPDATE_DATA case, you are not returning the updated state. This is causing the state to become undefined. The return statement inside the map callback returns the item in the array, and not the state.

    You can rewrite that case like this:

    case 'UPDATE_DATA': {
      const { id, data } = action.payload;
      return {
        ...state,
        data: state.data.map(item => {
          return item.uid === id ? data : item;
        }),
      };
    }