I'm very new to JavaScript/React in general and struggling with the concept of Promise
and async
.
First I have getSimById
, an API call in a JS file which returns a Promise
:
export function getSimById(simId) {
return fetch(simsUrl + "/results/" + simId, {
method: "GET",
headers: new Headers({
Authorization: "Basic " + base64.encode(login + ":" + password)
})
})
.then(handleResponse)
.catch(handleError);
}
And handleResponse
is an async function.
export async function handleResponse(response) {
if (response.ok) {
let someResponse = response.json();
return someResponse;
}
if (response.status === 400) {
throw new Error(error);
}
const error = await response.text();
throw new Error("Network response was not ok.");
}
Now I have a functional component which returns a Table
:
import React, { useState, useEffect } from "react";
import { getSimById } from "../api/outrightSimulatorApi";
function SimulationReport(props) {
const location = useLocation();
const [simResult, setSimResult] = useState([]);
useEffect(() => {
getSimById(location.state.simId).then(result => setSimResult(result));
}, []);
let reformattedData = getSimById(location.state.simId).then(
data => reformattedData = data?.markets?.length ? data.markets.reduce(
(accumulator, market) =>
market.selections.map(({ name, probability }, index) => ({
...accumulator[index],
"Team name": name,
[market.name]: probability,
})),
[],
) : null);
return (
<div>
<Table striped bordered hover size="sm" responsive>
<thead>
<tr>{
}
</tr>
</thead>
<tbody>{
}
</tbody>
</Table>
</div>
);
In this piece of code, I would like to map through reformattedData
as an array and ultimately map through its values in the returned Table
. However, reformattedData
is not an array in this instance, and is actually a Promise
. Because of this, whenever I try to access something like reformattedData[0]
it actually returns undefined
, and I am unable to map through its values in the Table
. How do I assign the Promise to a variable in this case so I can perform operations on it?