I am trying to output the players name from a JSON array using fetch and just returning it where I call it at for, I can insert the return into html elements.
The console logs the results I want perfectly but the return, returns undefined in the element.
JSON api example:
{
"PlayerID": 10000439,
"Jersey": 8,
"Position": "RF",
"FirstName": "Nick",
"LastName": "Castellanos"
}
HTML
<div id="scoreboard">
<div >TEAM1<span ></span>0</div>
<div >TEAM2<span ></span>0</div>
</div>
<div >
Batting:
<span id="batterPlayerName">
Player Name
</span>
</div>
<div >
Pitching:
<span id="pitcherPlayerName">
Player Name
</span>
</div>
JS
function PlayerName(id) {
var url = `https://apiurl/Player/${id}`;
fetch(url)
.then(response => response.json())
.then(data => {
console.log(`${data.FirstName} ${data.LastName}`)
return data.FirstName ' ' data.LastName;
})
}
var curBatter = document.querySelector('#batterPlayerName');
var curPitcher = document.querySelector('#pitcherPlayerName');
curBatter.innerHTML = PlayerName('10000439');
curPitcher.innerHTML = PlayerName('10000526');
console: Nick Castellanos PlayerName div: Batting: undefined
CodePudding user response:
You are attempting to set the value of PlayerName before the fetch has resolved.
If you return the promise from your PlayerName function then you are able to set the innerHtml once the promise is resolved.
function PlayerName(id) {
var url = `https://apiurl/Player/${id}`;
return fetch(url)
.then(response => response.json())
.then(data => {
console.log(`${data.FirstName} ${data.LastName}`)
return data.FirstName ' ' data.LastName;
})
}
PlayerName('10000439').then(player => {
var nameDiv = document.querySelector('#PlayerName')
nameDiv.innerHTML = `Batting: ${player}`;
})
Alternatively you can wrap the entire function to execute asynchronously
async function PlayerName(id) {
var url = `https://apiurl/Player/${id}`;
return fetch(url)
.then(response => response.json())
.then(data => {
console.log(`${data.FirstName} ${data.LastName}`)
return data.FirstName ' ' data.LastName;
})
}
var curBatter = document.querySelector('#batterPlayerName');
var curPitcher = document.querySelector('#pitcherPlayerName');
(async () => {
curBatter.innerHTML = await PlayerName('10000439');
curPitcher.innerHTML = await PlayerName('10000526');
})();
CodePudding user response:
You must declare the HTML selector to the belonging JSON