I'm learning api and request with fetch. I'm a student. I can't find why when i'm doing like my teacher, everything is going right, but when i have to adapt the code for my personnal working, it doen't work as i' m expecting ; lol...
I want to display on a web page my request result, i can get the array in my console but can't display it on my web page. Could someone help me to find a solution please. Thank you ! Regards.
const url = 'https://reqres.in/api/users?page=2';
async function getUsers() { const request = await fetch(url, { method: 'GET', });
if (!request.ok) {
alert("y'a une couille dans l'beurre!");
} else {
let datas = await request.json(); // on récupère les données en json et on en fait un objet js;
/* console.log(datas); */
document.querySelector('.users').textContent = datas.data[0];
console.log(datas.data);
}
// on va stocker fetch dans variable : const request;
//await veur dire qu'on va attendre fetch
}
getUsers();
by the way, you can't just display or inject an entire object
of data into the textContent
. datas.data[0]
is an object
of data. What you can do instead are:-
document.querySelector('.users').textContent = datas.data[0].email
document.querySelector('.users').innerHTML = `
<h2>${datas.data[0].first_name} ${datas.data[0].last_name} (ID: ${datas.data[0].id})</h2>
<p>${datas.data[0].email}</p>
`
datas?.data?.map((item) => {
let html = `
<h2>${item?.first_name} ${item?.last_name} (ID: ${item?.id})</h2>
<p>${item?.email}</p>
`;
document.querySelector(".users").insertAdjacentHTML("beforeend", html);
});
You can see a working example here: https://codesandbox.io/s/thirsty-hypatia-n3cpn?file=/src/index.js:484-722