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

Viewed 1265

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
}
2 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.

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

Related