How to update an object | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to update an object

I am having a object with use state hook Const [fruit,setFruit] = useState({ isApple :false, isOrange :false, }) How to change the value of isApple with setFruit function to true.

3rd Feb 2021, 6:34 PM
Sai Charan
Sai Charan - avatar
5 Answers
+ 2
setFruit({ ...fruit,isApple:true, })
3rd Feb 2021, 6:36 PM
Abhay
Abhay - avatar
+ 1
Sai Charan i can't tell without code what you are trying to do ,but e.target.value isn't specified when the fruit was set, so i am not sure if it will add new value to object or update some value which wasn't there . e.target.value has nothing to do with isApple , so setting it to true does nothing.
3rd Feb 2021, 6:48 PM
Abhay
Abhay - avatar
0
Abhay Thanks for answer but when I get e.target.value as isApple then it's not working
3rd Feb 2021, 6:40 PM
Sai Charan
Sai Charan - avatar
0
Sai Charan Try it with setFruit (f => {...f, isApple: e.target.value});
3rd Feb 2021, 10:53 PM
Calviղ
Calviղ - avatar
- 1
Abhay I tried it with setFruit ({... fruit,e.target.value:true})
3rd Feb 2021, 6:43 PM
Sai Charan
Sai Charan - avatar