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
left
andtop
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.
They way you propose may work only if the method validate()
returns an object.
In case that validate()
returns a string, array... the assignment setValues({ ...values, errors: err })
may break, since errors
is expecting an object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.