artworkjpm
artworkjpm

Reputation: 1337

update value inside array object

I only want to replace the name with the new name being typed in from the user. I'm using react redux typescript and its proving to be quite difficult. All the passed in arguments work, the newName and index, I just need to update the array object then return it with only the name in the index object changed.

My code:

Action:

export const updateName = (newName: string, index: number) => (
  dispatch: (arg0: { type?: string; newName: string; index: number }) => any
) => {
  dispatch({
    type: UPDATE_NAME,
    newName,
    index
  });
};

Reducer:

case UPDATE_NAME:
      return {
        ...state
        items[action.index].name: action.newName,

      };

State looks like this:

items: Array(50)
0: {id: "1d0b1095-f0b4-4881-8d5e-74c86d5beee2", name: "A Ipsum Debitis", participants: {…},
1: {id: "7384a574-1592-484e-9404-e876bf45410c", name: "Distinctio Blanditiis Voluptatibus Ut", participants: {…},

Upvotes: 1

Views: 935

Answers (1)

Drew Reese
Drew Reese

Reputation: 202608

Along with shallow copying the state object, you need to shallow copy any nested state that is being updated as well, i.e. state.items and the specific array element that is being updated.

case UPDATE_NAME:
  return {
    ...state,
    items: state.items.map((el, i) => i === action.index ? {
      ...el,
      name: action.newName,
    } : el),
  };

Upvotes: 1

Related Questions