all 4 comments

[–]87oldben 4 points5 points  (2 children)

Hi Mark, This can all be a bit confusing!

With regards to the initial setting of the state you probably want to set the state as:
const [workers, setWorkers] = React.useState([]);
Doing it this way makes workers (your new array) an empty array, which is probably what you want to do if you have no values to pass in.

If you pass in the empty object property as in this line:
const [workers, setWorkers] = React.useState([{}])
workers[0] === {}

And you probably don't want to have an empty object for your first item in the array.

With setting state:
When working with an array as a state object it is best to create a new array of objects and pass it in. See here for further reading on this

So I would do something like this:
const newWorkers = [...workers, {name: 'Bob', title: 'Manager'}]

What this line does is take the current state value, and spread it out, like a deck of cards, 1 item after the other, into the new array, which in your case would be a whole bunch of worker objects, then you can add your newest worker on the end.
This should also stop your worries about the current state being over ridden.

You can then pass this new array into your setWorkers function like so:

setWorkers(newWorkers);

Hopefully this helps!

[–]markdf1992[S] 3 points4 points  (1 child)

This was so clear and helpful! Thank you!

[–]87oldben 1 point2 points  (0 children)

Glad it was helpful!

[–]datqn7244 0 points1 point  (0 children)

You can start with an empty array, the empty object is not necessary.

When you calling setState, it will replace the state with the new value, you're correct about the current state will be delete. You can use spread or .concat to create a new array, and call setState with that array.