Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Saving data from API as string

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading