Guys i have this problem with my code
` get data
<script>
let dataBtn;
async function fetchData() {
const response = await fetch("./prodotti.json");
return await response.json();
}
const container = document.querySelector(".container");
const btn = document.querySelector("#get");
const newDiv = document.createElement("div");
btn.addEventListener("click", async () => {
const data = await fetchData();
//console.log(data);
container.appendChild(newDiv).innerHTML = data.name;
});
</script>
`
when i click on the button appears [object object] instead of the json data
CodePudding user response:
It looks like you get a problem with serialisation of an object what you received from your api. Make sure the data.name is really a string and accessible.Below a working example with another example api to show that your code will work.
let dataBtn;
async function fetchData() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
return await response.json();
}
const container = document.querySelector(".container");
const btn = document.querySelector("#btnGet");
const newDiv = document.createElement("div");
btn.addEventListener("click", async () => {
const data = await fetchData();
console.log(data);
container.appendChild(newDiv).innerHTML = data.title;
});
<div ></div>
<button id="btnGet">GET</button>
CodePudding user response:
Try to write code like this: data[0]