Home > Blockchain >  React state not updating with values passed to the function
React state not updating with values passed to the function

Time:01-16

I am trying to implement a form which will be used to calculate a golf score. I was thinking the structure of the state will have the hole number as the key, and the par and score values for that hole as the values in an object. This is what that looks like:

const [scores, Setscores] = useState({
    1: { par: 3, score: 3 },
    2: { par: 4, score: 5 },
  });

I have a form which accepts two input values where the user can enter the 'par' and 'score' values for each hole. I am trying to update the state so that when the user enters values in these fields, a new object is added to the state where the hole number is the key, and the par and score values as the value as can be seen above.

To do this, onChange of the input value, I pass the inputed value and the hole number to the handleScores function which then updates the state. This is the code that I currently have:

<input
   name={"hole1Par"}
   type="int"
   placeholder="Par"
   onChange={(e) => handleScore( e.target.value, 3)}
></input>


const handleScore = (parNumber, holeNumber) => {
    Setscores({ ...scores, holeNumber: { par: parNumber } });
};

For some reason the state ends up looking like this:


{
    1: { par: 3, score: 3 },
    2: { par: 4, score: 5 },
    holeNumber: { par: 6 }
  }

the key is not being updated with the value which is passed to the function and instead has the word as the key. I have checked and both values that are passed to the function are numbers. What exactly am I doing wrong?

CodePudding user response:

You have to use holeNumber in Setscores({ ...scores, holeNumber: { par: parNumber } }); instead [holeNumber].

Try This;

Setscores({ ...scores, [holeNumber]: { par: parNumber } });
  • Related