Reputation: 149
i'm working on a corona data app for school and I want to sum the amount of tests and positive results from an API.
Here is my code:
function GetDataApi() {
if(data !== null) {
const filter = data?.filter((item => item.Date_of_statistics === '2021-04-01'));
filter.forEach((item, index) => {
setUseTestedResult(parseInt(useTestedResult) + parseInt(item.Tested_with_result));
setUsePositiveData(parseInt(usePositiveData) + parseInt(item.Tested_positive));
});
}
}
It only returns the numbers of the last object in the array. It looks like the setState function isn't working.
Upvotes: 1
Views: 170
Reputation: 1075925
State updates are asynchronous. You're repeatedly updating your state, overwriting previous updates, so you end up storing only the result of the last call to your state setters.
Instead, build the sum, then set the result:
function GetDataApi() {
if (data !== null) {
// No ? here −−−−−−−−−−−−v
const filteredData = data.filter((item => item.Date_of_statistics === '2021-04-01'));
let testedSum = 0;
let positiveSum = 0;
for (const {Tested_with_result, Tested_positive} of filteredData) {
testedSum += Tested_with_result;
positiveSum += Tested_positive;
}
setUseTestedResult(previousValue => previousValue + testedSum);
setUsePositiveData(previousValue => previousValue + positiveSum);
}
}
A couple of notes:
I've removed the parseInts
, hopefully the data you're using is already numeric, but add them back if you need them. Only parse strings, don't call parseInt
on numbers.
Note that I replaced the optional chaining (?.
) with normal chaining (.
), since you've just tested that data
isn't null
and if it's undefined
, your subsequent code would fail anyway.
Your code was adding the sum from data
's entries to the existing state member's value, so that's what I've done above, using the callback form of the state setters (since any time you use existing state to set new state, you should use the callback form). But to me it seems a bit odd to be adding this information to an existing state member, rather than replacing it.
Upvotes: 3