born2gamble
born2gamble

Reputation: 207

Reactjs, is setState needed here, changing value of an object in state

My question is, is it ok to not use setState in this situation or if I should, how would I go about it?

I'm creating a sportsbetting app.

On the list of games, when a user clicks on Denver Broncos -3, a bet slip is created. This also calls
setState({gameSelected:[item]}) in the Parent Component.

It stores that object and adds to it using the spread operator when more bets are clicked.

I pass down that data to betSlip.js file.

side note Some of the data in the gameSelected object has :
risk:'',
win:'',

On betSlip.js I am looping through that data and displaying it.

Relevant code inside the loop.

<input type="text" placeholder="Risk" onChange={(e)=>this.handleBet(e,item)}/>
<input type="text"  placeholder="Win" value={item.win}/>

This function is inside betSlip.js

 handleBet = (e,item) =>{

      let bet=e.target.value
    //function to calculate moneyline bet
      let calcBet =(bet)=>{
          let newAmount =(100/item.juice)*bet;
          return newAmount
      }

      item.win = calcBet(bet)


    }

Upvotes: 0

Views: 51

Answers (1)

Tyler
Tyler

Reputation: 2390

Yes, you should be using setState here to update item.win. Otherwise, React is not aware of the mutation on item and does not rerender. Since item is a prop, you should treat it as immutable from within betSlip.js and update item.win through an event handler in the parent component where item is maintained. Your betSlip.js component could have an onWinUpdate handler that is called within handleBet as this.props.onWinUpdate(item, calcBet(bet)). Then, the parent component can have a function handleWinUpdate(item, bet) that updates the state. I would also keep things immutable in handleWinUpdate by doing something like this:

handleWinUpdate(item, bet) {
  this.setState(state => ({
    gameSelected: state.gameSelected.map(i => {
      if (i === item) {
        return { ...i, win: bet };
      } else {
        return i;
      }
    })
  }));
}

Notice that we are setting gameSelected to a new array and replacing item in that array with a new copy of item, but with a new win value. No objects are ever mutated.

Even though you don't have to use immutability here, I find it easier to reason about and it opens the door for performance gains later using things like React.PureComponent that rely on immutability.

Upvotes: 1

Related Questions