Search code examples
reduxreact-redux

How Do I Update a Property in Array of Objects using Redux Reducers?


I am currently trying to update the text value using Redux reducers. However, I am having trouble figuring out how exactly I would modify the text of a specific object in the array. Here is what I have so far:

export const teamSlice = createSlice({
  name: "team",
  initialState: {
    teamArr: [
      { id: " 1", text: "", icon: "" },
      { id: " 2", text: "", icon: "" },
      { id: " 3", text: "", icon: "" },
      { id: " 4", text: "", icon: "" },
      { id: " 5", text: "", icon: "" },
      { id: " 6", text: "", icon: "" },
      { id: " 7", text: "", icon: "" },
      { id: " 8", text: "", icon: "" },
      { id: " 9", text: "", icon: "" },
      { id: " 10", text: "", icon: "" },
    ],
  },
  reducers: {
    setTeamSlice: (state, action) => {
      state.teamArr = action.payload
    },
    setPlayerTextSlice: (state, action) => {
      const updatedArr = [...state.teamArr]

      //get object and index position of object
      const player = updatedArr.filter(
        (obj) => obj.id === ???
      )[0]
      const index = updatedArr.indexOf(player)

      //update text of object
      player.text = action.payload

      //update object in array
      updatedArr[index] = player

      //return the new updatedArr as the result
      return updatedArr
    },
  },
})

The function I thought of creating to update the text property was setPlayerTextSlice. However, I cannot find out a way to get the ID of the object I am interested in when the function is called.

I will also be calling this function from an input field that will use this function onChange:

<input
        onChange={(e) => setPlayerTextSlice(e.target.value)}
        value={text}
        placeholder={id}
      ></input>

Any help and advice is greatly appreciated!


Solution

  • You can just do

      setPlayerTextSlice: (state, action) => {
          const player = updatedArr.find(
            (obj) => obj.id === action.payload.id
          )
          if (player) {
            player.text = action.payload.text
          }
        },
    

    the rest of your code is actually not required.

    You can call it with dispatch(setPlayerTextSlice({ id: 5, text: "foo" }))