4

I want to update my key value of comment to a new value, while keeping the other keys as is. I know I'll probably need spread operator ... but I'm not sure the exact syntax. What would I need to put in setResource() to accomplish this?

const VideoPage = () => {
  const [state, setResource] = useState(
    {
      video: 'placeholder'
      loading: 'placeholder'
      comment: 'placeholder'
    }
  )
  const funct = () => {
    setResource()
  }
}
Robert C
  • 756
  • 10
  • 25

2 Answers2

18

If you want to keep other parts of the state you should do something like this:

setResource(prevState => ({
    ...prevState,
    comment: "new Value",
}))

Since the setter function for your state does not merge other values like the old setState method. This is why you should do a functional update.

devserkan
  • 16,870
  • 4
  • 31
  • 47
2

Spread your object as it is and then update you required value.

const VideoPage = () => {
  const [state, setResource] = useState(
    {
      video: 'placeholder'
      loading: 'placeholder'
      comment: 'placeholder'
    }
  )
  const funct = () => {
    setResource({...state, comment:'Hello'})
  }
}
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
  • I'm not quite sure spreading the current state directly is the right way here. At the end of the day, we are using the current state and updating it with the new value. Using functional updates maybe is a better idea. – devserkan Dec 13 '19 at 15:29