0

I have a table that maps through a state that is set to an array of users. The users are retrieved from a server and database, however, I'm only getting one user added to the state when there are two total.

This is how I'm adding users to the state:

const [customerAccounts, setCustomerAccounts] = useState([]);

for(let i = 0; i < res.data.customerAccounts.length; i++) {
  setCustomerAccounts([...customerAccounts, res.data.customerAccounts[i]]);
}

When I log each index of res.data.customerAccounts I get both accounts logged, but only one is displayed in the table, and when I log the state with a button I also only see one, and it's always the second one (index 1, not 0). What could be the reason for this?

Phil
  • 157,677
  • 23
  • 242
  • 245
Darkshadowtrail
  • 208
  • 1
  • 10
  • This would be much cleaner as simply `setCustomerAccounts((prev) => prev.concat(res.data.customerAccounts))` – Phil Aug 12 '22 at 01:04
  • Or "setCustomerAccounts([...customerAccounts, ...res.data.customerAccounts]);" – Jeffrey Ram Aug 12 '22 at 01:06
  • 1
    @JeffreyRam not recommended. Updating state based on the current value should use [functional updates](https://reactjs.org/docs/hooks-reference.html#functional-updates) – Phil Aug 12 '22 at 01:07
  • @Phil That works in getting all users in the table, but it renders users twice. Any way to run the hook once? – Darkshadowtrail Aug 12 '22 at 01:14
  • If you don't want to build up your array every time the code above runs, then simply use `setCustomerAccounts(res.data.customerAccounts)`. I'm guessing you've got the above in an effect hook and it's [running twice due to strict mode](https://stackoverflow.com/q/61254372/283366) – Phil Aug 12 '22 at 01:21

0 Answers0