Fetch Confusion

fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.log(error);
});
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.log(error);
});
I am learning JS. My question is when i am getting this object from fetch how do i use it outside fetch suppose i have to display all the names from the data on the webpage. how do i do that?
4 Replies
Joao
Joao14mo ago
Inside the second then block. When working with Promises, which basically is JavaScript's lingo for "variables that will eventually hold some value", you have to wait for them and only until then you can use them in your app. For example:
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json();
})
.then((users) => {
users.forEach(user => {
const p = document.createElement('p');
p.textContent = user.name;
document.body.appendChild(p);
});
})
.catch((error) => {
console.log(error);
});
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json();
})
.then((users) => {
users.forEach(user => {
const p = document.createElement('p');
p.textContent = user.name;
document.body.appendChild(p);
});
})
.catch((error) => {
console.log(error);
});
Obviously this is as simple as it gets, but the point if that you have to work inside the then block. Note that other parts of the code will not have access to users (btw I renamed that parameter name to better reflect what is holds, as "data" was too generic).
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.log(error);
});

console.log(users); // won't work!
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.log(error);
});

console.log(users); // won't work!
There's also an alternative syntax called async/await where you can specify the code to wait until it resolves. It's the same thing, but written differently and in such a way that looks like regular, synchronous code.
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
console.log(data);
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
console.log(data);
Usually you use this syntax within functions, and you have to explicitly label them as async but I think since Node 18 you can use await at the top level.
async function getUsers() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
return data;
}

const users = await getUsers();
console.log(users);
async function getUsers() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
return data;
}

const users = await getUsers();
console.log(users);
Israr
IsrarOP14mo ago
Ahhh, Thank you sooo much Soo, if I use .then I won't be able to use the data outside and if i use async function and hold it in a variable with await I'll be able to use it globally That's correct? Am getting this error
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at new index.html:21:23)
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at new index.html:21:23)
This worked
let globalUserData;

async function getUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
globalUserData = data;
} catch (error) {
console.log(error);
}
}

async function fetchData() {
try {
await getUsers();
} catch (error) {
console.log(error);
}
}

fetchData();
let globalUserData;

async function getUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
globalUserData = data;
} catch (error) {
console.log(error);
}
}

async function fetchData() {
try {
await getUsers();
} catch (error) {
console.log(error);
}
}

fetchData();
but i want to know if this is the right way of getting the data ?
Joao
Joao14mo ago
Yes, that's how you do it. There are other things you can consider for more complicated situations where you want to be able to abort a request or continuously repeat it every few seconds, and things like that. But at its core that's how simple it really is. One thing you should know however is that sometimes you may make a request to a resource that for whatever reason is not available or does not exist. In those cases there will be no error thrown, and your catch block will not run. You need to explicitly check if the request was ok:
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
if (!response.ok) {
return [];
}
return response.json();
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.log(error);
});
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
if (!response.ok) {
return [];
}
return response.json();
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.log(error);
});
Here, response.ok simply checks if the status code is anything other than a 200 (which is standard convention accepted as "everything is ok"). The fact that a request returned a 404 does not meant that the request failed: it did what you asked for, make arequest and give you a response, but it simlpy wasn't the response you were expecting so you must explicitly check for that yourself.
Israr
IsrarOP14mo ago
That helps, thank you sooo muchh ❤️ @Joao
Want results from more Discord servers?
Add your server