Why is the p variable showing as undefined when setting the innerText of the name element to p.name?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="usname"> </p>
<script>
const p="";
const app= async()=>{
const data= await fetch("https://api.github.com/users/Anup-maurya");
const p= await data.json();
console.log(p);
}
app();
const name=document.getElementById("usname");
name.innerText=p.name;
</script>
</body>
</html>
The issue you’re encountering is related to the asynchronous nature of JavaScript. When you try to access p.name
immediately after calling app()
, the p
variable hasn’t been assigned the fetched data yet because await fetch()
is still pending. As a result, p
remains an empty string (""
) when you access it outside the app()
function.
To fix this, you need to set the text content of the <p>
element inside the app()
function after you have fetched and processed the data. Here’s the corrected code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="usname"> </p>
<script>
const app = async () => {
try {
const data = await fetch("https://api.github.com/users/Anup-maurya");
const userData = await data.json();
console.log(userData);
const nameElement = document.getElementById("usname");
nameElement.innerText = userData.name;
} catch (error) {
console.error("Error fetching data:", error);
}
}
app();
</script>
</body>
</html>
In this corrected code:
- The
nameElement.innerText = userData.name;
line is moved inside theapp()
function after the data has been fetched and processed. - I’ve renamed the variable
p
touserData
to make it clearer that it contains the fetched user data.
This way, the <p>
element’s text content will be set to the user’s name after the data has been successfully fetched and processed.