Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In react hooks how do I pass a newly created object to a state object?

How do I pass err to errors : {} here ?

const data = { name: "", errors: {} }
const [values, setValues] = useState(data)
const handleSubmit = () => {
     const err = validate();  // I receive an object in err
    setValues({ ...values, errors: err }) // I cant set err to //errors: {} above
}
like image 880
Sushilzzz Avatar asked Nov 14 '25 19:11

Sushilzzz


1 Answers

From React DOCs - State Hook, we get that:

State variables can hold objects and arrays just fine, so you can still group related data together. However, unlike this.setState in a class, updating a state variable always replaces it instead of merging it.

Also, from Hooks FAQ:

Now let’s say we want to write some logic that changes left and top when the user moves their mouse. Note how we have to merge these fields into the previous state object manually:

function handleWindowMouseMove(e) {
     // Spreading "...state" ensures we don't "lose" width and height
     setState(state => ({ ...state, left: e.pageX, top: e.pageY }));
   }

Therefore, the way you're currently doing it is correct.

like image 147
cbdeveloper Avatar answered Nov 17 '25 07:11

cbdeveloper



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!