1

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: {…},

1 Answer 1

1

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),
  };
Sign up to request clarification or add additional context in comments.

2 Comments

I get this message "(parameter) el: never Spread types may only be created from object types.ts(2698)"
@artworkjpm Yup, exactly, you need to type the map callback function. Seems el would have a type similar to { id: string, name: string, participants: any }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.