0

I'm really struggle to understand where this code goes wrong. I can't concat two times in a row because it turns my array into an object. Here is the code...

this.setState((prevState) => ({
      //Add new bet to users array of bets
      usersByName: {
        ...prevState.usersByName,
        [newBet[0].name]: {
          ...prevState.usersByName[newBet[0].name].concat(newBet),
          amountleft: prevState.usersByName[newBet[0].name].amountleft - newBet[0].amount,
          lastweekroi: prevState.usersByName[newBet[0].name].lastweekroi,
          thisweekroi: prevState.usersByName[newBet[0].name].thisweekroi,
        },
      },
    }))

The initial structure is correct and looks like this.

enter image description here

When I run the setstate command it changes the structure to this, which I can't then run concat again because I get the error .concat is not a function

enter image description here

Does anyone see a way to fix this? Arrays, JSON and this stuff is confusing. Thanks

MomasVII
  • 4,641
  • 5
  • 35
  • 52
  • 1
    When you spread in an object, you're going to get an object back. You can try pushing it onto your array instead. Are you using redux? Overall, this is too much state to hold in a single component state, imho. Even moving to `useState` would allow you to have more slices of state that could be updated individually, which would probably also simplify this. – jmargolisvt Mar 29 '21 at 21:46
  • Unfortunately given my experience redux is something that is too daunting of a task to start at the moment. What are the downsides to what i'm doing. Just code legibility? speed? performance? Thanks – MomasVII Mar 29 '21 at 23:17
  • Any suggestions in terms of code. I'm trying everything and getting no where – MomasVII Mar 30 '21 at 01:37
  • 1
    The downside is that it's complicated to update, as you are finding out. No redux required here if you really want all this state local to your component. This might help you see how arrays are managed with useState: https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate – jmargolisvt Mar 30 '21 at 03:02
  • Does this answer your question? [Push method in React Hooks (useState)?](https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate) – juliomalves Apr 01 '21 at 16:31

0 Answers0