The following code has a button to add inputs and another button to add all of the values in the inputs assuming they are numbers. The last line is to display the sum of everything. However, for some reason it only gets the value of the last input. It also does not reset. I thought having the setGrade(0) would do this but it just keeps adding the last number without resetting.
I would just like to know why this is the case with the following code. The id for the input fields are just the number starting from 1.
function Start(){
const [rows, setRows] = useState([]);
const [inputNum,setNum] = useState(1);
const [totalGrade, setGrade] = useState(0);
const addInput = () =>{
setNum(inputNum+1);
setRows(rows.concat(<Inputs key={rows.length} label={inputNum.toString()}></Inputs>));
}
const addGrade = () =>{
setGrade(0);
for(let i =0;i<rows.length;i++){
setGrade(parseInt(document.getElementById((i+1).toString()).value,10) +totalGrade)
}
}
return(
<div>
<h1>Calculate your GPA!</h1>
{rows}
<button class="button2"onClick={addInput}>Add Input</button>
<button class="button2"onClick={addGrade}>Compute Grade</button>
<h2>Grade: {totalGrade}</h2>
</div>
);
}