0

I have a state that should be a dictionary like so:

[personInfo, setPersonInfo] = useState({"firstName": "", "lastName": ""});

I want to update this state like so:

setPersonInfo(prevPersonInfo => prevPersonInfo["firstName"] = "name")

But this is not working.

Please do not recommend that I store two separate states for firstName and lastName. For my particular use case, it is necessary that I use a dictionary.

  • 4
    That is not immutable way to set state, so instead, return the object using ...rest and your changed key: value. setPersonInfo(ppi => ({...ppi, firstName: 'name'})) – George Jul 27 '20 at 19:52
  • what you do is mutating the object (which is a big NO NO in react land), you have to create a new brand object like so setPersonInfo(prev => {...prev, firstName: 'SOME_NAME'}) – AngelSalazar Jul 27 '20 at 19:52 
3

My guess is that it isn't working because you are altering the same object, instead of returning a new one. I'd recommend rewriting it in a way that spreads into a new object

setPersonInfo(prevPersonInfo => ({...prevPersonInfo, firstName: "name"}))

Incidentally, depending on how complex your object is getting you might want to consider useReducer.