I’m having trouble saving the return output from my getLastMatchData() function outside of the function itself. Tried a bunch of different things but to no result. Any help would be very appreciated!
import fetch from "node-fetch";
const premier_League_Id = '39'
const tottenhamId = '47'
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'REDACTED',
'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com'
}
};
function getLastMatchData() {
fetch('https://api-football-v1.p.rapidapi.com/v3/fixtures?season=2022&team=47&last=1', options)
.then(response => response.json().then(data =>{
let generalLastMatchData = data['response'];
let leagueName = generalLastMatchData[0]['league'].name;
let teamNames = generalLastMatchData[0]['teams'];
let homeTeam = teamNames['home'].name;
let awayTeam = teamNames['away'].name;
return [homeTeam, awayTeam];
}))
}
const lastMatchNames = getLastMatchData();
console.log(lastMatchNames);
>Solution :
You are not returning anything from the getLastMatchData function. Update it to this:
function getLastMatchData() {
// You were not returning the return value of the fetch call
return fetch( "https://api-football-v1.p.rapidapi.com/v3/fixtures?season=2022&team=47&last=1", options).then(res => res.json()).then(data => {
let generalLastMatchData = data["response"];
let leagueName = generalLastMatchData[0]["league"].name;
let teamNames = generalLastMatchData[0]["teams"];
let homeTeam = teamNames["home"].name;
let awayTeam = teamNames["away"].name;
// This return value is for the Promise returned by the fetch call
return [homeTeam, awayTeam];
})
}
Use it like this:
// data is an array that contains "homeTeam" on index 0 and "awayTeam" on index 1
getLastMatchData().then(data => console.log(data))
You need to use .then as the function returns a Promise.