'Using a promise with Fetch API response still has my data returning as undefined
I am building a simple web app that allows users to search the stats of a player in a video game.
Here is my code
let player = [];
let proxy = "https://cors-anywhere.herokuapp.com/"
let url = proxy + "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=Hess"
function getPlayer() {
return fetch(url)
.then((response) => response.text())
.then((data) => console.log(data));
}
getPlayer().then((playerData) => {
console.log(playerData);
playerData.push(player);
console.log(player);
});
As you can see, I am trying to console.log the response and push the response to an array player so I can later use the fecthed data in the player array to perform some other actions on.
Why is it returning undefined? Why won't my response get pushed into the player array?
Solution 1:[1]
let player = [];
let proxy = "https://cors-anywhere.herokuapp.com/"
let url = proxy + "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=Hess"
function getPlayer() {
return fetch(url)
.then((response) => response.text())
.then((data) => {
console.log(data)
return data;
});
}
getPlayer().then((playerData) => {
console.log(playerData);
player.push(playerData);
console.log(player);
});
You need to make sure you are returning a value at each step of your .then(). And your .push is the wrong way round
Solution 2:[2]
as i see it you probably switch by mistake here the array and the data in the code below you accidentally push the array to the playerData and not the opisite
playerData.push(player);
you shoud do this player.push(playerData)
and I think you should also remove the second then if you console log it as the people says here to get data but i think you can also use the first then and if you want the second one just do this:
function getPlayer() {
return fetch(url)
.then((response) => response.text())
.then((data) => data);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahul Bhobe |
| Solution 2 | TalOrlanczyk |
