I have created a function named fetchJSONData()
that is supposed to return a JavaScript object from the URL you give it, and when you console.log the output, it works as expected, but when I try to access a property from the returned object, it shows undefined
as the property value.
Here is the small json file I am using:
{
"headerText": "Lorem Ipsum",
"subText": "lorem ipsum dolor sit amet....."
}
Here is a very basic example code snippet:
async function fetchJSONData(url) {
var response = await fetch(url);
var data = await response.json();
console.log(data);
return data;
}
var textTest = fetchJSONData("https://jsonplaceholder.typicode.com/posts/1");
var test01 = document.getElementById("test01");
var test02 = document.getElementById("test02");
window.onload = function() {
// Returns undefined
test01.innerText = textTest.title;
test02.innerText = textTest.body;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1 id="test01">blank</h1>
<p id="test02">blank</p>
</body>
</html>
You can see when I try to access the variables, the html elements show the value is undefined.