0

I am looking to update value(s) in a nested object based on user input. So for instance, if the user chooses to update their country and street, only those values will be passed as the action.payload to the reducer and updated (the rest of the state will be kept the same). I provide my initial state and reducer:

My state:

const initialState = {
  userData: [
    {
      firstName: "",
      lastName: "",
      country: "",
      address: {
        street: "",
        houseNumber: "",
        postalCode: "",
      }
    }
 ],
  error: null,
};


export default (state = initialState, action) => {
  switch (action.type) {
    case GET_USER_DATA:
      return { ...state, userData: action.payload };
    case UPDATE_USER_DATA:
      return {
        ...state,
        userData: [{
          ...state.userData,
          ...action.payload,
       }]
      };
    default:
      return state;
  }
};

Any help would be great, thank you!!

critical_maas
  • 127
  • 1
  • 3
  • 9
  • So what do you need ? You already have the reducer, do you have any error or something ? – Quentin Grisel Jun 22 '20 at 14:47
  • I was able to find the problem, but in future questions you should make the problem and question clearer. There is actually no question here, which makes it hard for people to help. – Brian Thompson Jun 22 '20 at 14:58

1 Answers1

0

It doesn't appear that you need the array wrapping the object. If that is true, remove it for simplicity. Then userData becomes a plain object, and your update becomes:

return {
  ...state,
  userData: { // <- no wrapping array, just update the object
    ...state.userData,
    ...action.payload,
  }
};

Since there is an array, you would need to destructure the object at the correct index.

return {
  ...state,
  userData: [{
    ...state.userData[0], // <- destructure the object, not the array
    ...action.payload,
  }]
};

If you do need the array, and there will be more than one object, you will also need to pass an identifier in the action payload in order to know which index to update, but with the current information given this is the most complete answer possible.

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
  • Seems like you have good expertise on the topic. Think you can help help me here? https://stackoverflow.com/questions/72400551/jest-cannot-change-context-when-action-is-dispatched – sayayin May 28 '22 at 16:57