I’m trying to retrieve data from an Api.
When I log the response data, everything looks fine. When i load my component I get ‘undefined’ on each place where I should have data from the Api. When I press on my sidebar, every ‘undefined’ turns into the right data. I think that I encounter some problem with the asynchronous behaviour of my calls but I don’t realy know how to solve this problem.
For information : I’m using ReactJs
function Dashboard() {
const [isLoading, setIsLoading] = useState(true);
const [loadedDataFromApi, setLoadedDataFromApi] = useState([]);
//some other vars
useEffect(() => {
setIsLoading(true);
fetch(`https://soccer.sportmonks.com/api/v2.0/fixtures/between/${todayString}/${inTenDaysString}?api_token=oAF3XOevLeC24Zjuzvu56vfOfvyrmHSd11eHr4Ij6ifeJq563NzHeKFrLaJy`
)
.then((response => {
return response.json();
}))
.then((response => {
//FOREACH to loop over every {} in the []
response.data.forEach((data) => {
var localTeam = data.localteam_id;
var visitorTeam = data.visitorteam_id;
var docRef1 = db.collection("Teams").doc(`${localTeam}`)
var docRef2 = db.collection("Teams").doc(`${visitorTeam}`)
docRef1.get().then((doc) => {
if (doc.exists) {
data.localTeam = doc.data().name;
data.logoLocalTeam = doc.data().logo;
} else {
// doc.data() will be undefined in this case
console.log("No such Team found!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
docRef2.get().then((doc) => {
if (doc.exists) {
data.visitorTeam = doc.data().name;
data.logoVisitorTeam = doc.data().logo;
} else {
// doc.data() will be undefined in this case
console.log("No such Team found!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
})
setLoadedDataFromApi(response.data);
setIsLoading(false);
}))
}, [todayString, inTenDaysString])
// if we are loading the data return loading ..
if (isLoading) {
return (
<section>
<p>Loading ...</p>
</section>)
}
return (
// some code )