I want to calculate the total sum of "stopTime" in this object.
I have some problems resolving this, I have searched far and wide without any success.
My API response looks like this:
[
{
"id": 1,
"stopCause": "Stop Cause 1",
"stopTime": 3,
"stopOperator": "Somebody",
"createdAt": "2023-06-26T10:29:31.000Z",
"updatedAt": "2023-06-26T10:29:31.000Z",
"OrderId": 1
},
{
"id": 2,
"stopCause": "Stop Cause 3",
"stopTime": 5,
"stopOperator": "Somebody",
"createdAt": "2023-06-26T10:29:37.000Z",
"updatedAt": "2023-06-26T10:29:37.000Z",
"OrderId": 1
},
{
"id": 3,
"stopCause": "Stop Cause 4",
"stopTime": 12,
"stopOperator": "Username",
"createdAt": "2023-06-28T06:45:24.000Z",
"updatedAt": "2023-06-28T06:45:24.000Z",
"OrderId": 1
}
]
and here is the code to sum up "stopTime" :
const totalStopTime = stopTime.reduce(
(acc, curr) => acc + parseInt(curr.stopTime),
0
);
This would all work fine and dandy if there wasn’t any delay from the API call… It always resolves into 0, because the API is slower than the page loading…
Is there any way to get around this?
2
Answers
When dealing with API responses you should use async/await to resolve issues due to such asynchronous responses. You need to change your code structure to something like this:
The call to
simulateAPICall()
function should be replaced by the actual API call.Basically, due to the
await
keyword before api call, the control waits for the assignment before moving forward making that part synchronous-like.Note that
await
can only be used inside anasync
function.Read more about this here or here.
You haven’t shared your fetch call but in general you can’t await for an
asynchronous
call in React. You need to do a little bit of a hack withuseEffect
to populate some state withuseState
. You can then use the state to trigger auseMemo
to conditionally calculate some operation (i.e.,Array.reduce()
)If you use
fetch
then you can replace thefetchStopTime
function withHope this helps!