skip to Main Content

I am trying to make a basketball scoreboard app in React and have each team as it’s own object with score, field goals made, and field goal attempts as properties. I have buttons that increment all of these properties and I am trying to create a button to account for missed shots using setState on field goal attempts(fga), but it also updates the state for the other properties resetting their state to 0. Is there a way to use setState on a specific property without touching the rest?

Object:

  const [team1, setTeam1] = useState({
    score: 0,
    fgm: 0,
    fga: 0,
    threePm: 0,
  });

Button:

       <button
          id="miss"
          onClick={() =>
            setTeam1({
              fga: team1.fga + 1,
            })
          }
        >
          Miss
        </button>

3

Answers


  1. Take the previous state, spread it, and add the updated property to create the new state:

    onClick={() =>
      setTeam1(team1=> ({
        ...team1,
        fga: team1.fga + 1,
      }))
    }
    

    When creating a new state, based on the previous state, it’s better to use and updater function. The updater function is called with the previous state. Take the previous state, spread it into a new object, and add the updated property:

    onClick={() =>
      setTeam1(prev => ({
        ...prev,
        fga: prev.fga + 1,
      }))
    }
    
    Login or Signup to reply.
  2.     // Define an object with multiple properties
    let person = {
      name: 'John',
      age: 25,
      occupation: 'Engineer'
    };
    
    // Update only the 'age' property while keeping others unchanged
    let updatedPerson = {
      ...<link>person</link>,  // Spread the properties of the original object
      age: 26    // Update the 'age' property
    };
    
    // Output the updated object
    console.log(updatedPerson);
    
    Login or Signup to reply.
  3. Simple, use a spread operator to make a copy of the previous state and set it to your new state, then we set the new property like so:

    <button id="miss"
      onClick={() => setTeam1({...team1, fga: team1.fga + 1})}
    >
     Miss
    </button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search