Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
58
rated 0 times [  60] [ 2]  / answers: 1 / hits: 9116  / 4 Years ago, mon, july 27, 2020, 12:00:00

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.


More From » reactjs

 Answers
5

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.


[#3054] Saturday, July 25, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;