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
}
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
leftandtopwhen 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With