Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set state in nested object

Would like to know if there is a way to update nested object states in React using useState()

import React, {useState} from 'react'

const MyComp = () => {

  const [colors, setColors] = useState({colorA: 'RED', colorB: 'PURPLE'});

  return (
    <div>
       <span>{colors.colorB}</span>
       <button onClick={() => setColors({...colors, colors: { colorB: 'WHITE'}})}>CLICK ME</button>
    </div>
  )
}


export default MyComp;

I was thinking to use useReducer() but I read that It's normally use for more complex states and maybe there is a solution for this case just using useState()

Any ideas?

Thx in advance

like image 289
Kaiser91 Avatar asked Mar 19 '26 14:03

Kaiser91


2 Answers

colors already is the whole object, you don't need to declare as a property.

spread the original object and override colorB

() => setColors({...colors, colorB: 'WHITE'}) 
like image 105
Dupocas Avatar answered Mar 21 '26 05:03

Dupocas


You are updating the state in a wrong way. Change your button statement to below,

<button onClick={() => setColors({...colors, colorB: 'WHITE'})}>CLICK ME</button>
like image 34
Gangadhar Gandi Avatar answered Mar 21 '26 05:03

Gangadhar Gandi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!