dimanche 2 février 2020

fetching with response from a previous fetch

I am currently trying to call an API with the response of a previous API fetch.

First, I call the method fetchRoster. Then, for every player on the roster (NHL), I would love to use it's id to fetch his stats from another endpoint.

var roster = await fetchRoster(8);


roster.map((player) => {
  console.log(player.person.id);
  console.log(player.person.fullName);

  var stats = getPlayerStats(player.person.fullName);
  console.log(stats);
})

This is the method fetchRoster() that I call first to get the IDs of the players.

function fetchRoster(id) {
    try {
        //let response = await fetch(`${roster_base_url}/${id}/roster `);
        let response = await fetch('https://statsapi.web.nhl.com/api/v1/teams/' + id + '/roster');
        let responseJson = await response.json();
        return responseJson.roster;
    } catch(error) {
        console.log(error);
    }
}

This is the method getPlayersStats that is called after obtaining the id from the first API response.

export async function getPlayerStats(id) {
try {
    let response = await fetch('https://statsapi.web.nhl.com/api/v1/people/' + id + '/stats?stats=statsSingleSeason&season=20192020');
    let responseJson = await response.json();
    return responseJson.stats[0].splits[0].stat;
} catch(error) {
    console.log(error);
}
}

)

However, it seems that the first response isn't arrived yet when calling the 2nd API. Does anyone have a solution for that?

Thanks in advance guys




Aucun commentaire:

Enregistrer un commentaire