4

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
}
Sushilzzz
  • 527
  • 5
  • 20
  • I'm not sure if the function is case-sensitive, does it work if you use `useState` instead of `usestate`? Your use of `setValues()` to set `errors` looks correct to me. – rickdenhaan Jun 23 '19 at 16:10
  • the spelling is correct in my VS code – Sushilzzz Jun 23 '19 at 16:12
  • 1
    The current code would work fine, if validate is a synchronous method – Shubham Khatri Jun 23 '19 at 16:14
  • 4
    Seems to work just fine: https://codesandbox.io/s/sparkling-tree-9tuh1 -- whatever the problem is, it's not with this part of your code. – rickdenhaan Jun 23 '19 at 16:17
  • Take a loot at this question about updating nested objects with `useState` hook: [Link](https://stackoverflow.com/questions/55342406/updating-and-merging-state-object-using-react-usestate-hook) – cbdeveloper Jun 23 '19 at 21:11
  • Or piggybacking on @ShubhamKhatri with async/await: https://codesandbox.io/s/dreamy-tree-e4lgf – vol7ron Jun 24 '19 at 01:19

2 Answers2

2

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.

Community
  • 1
  • 1
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
0

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

Alberto S.
  • 1,805
  • 23
  • 39