The Fetch API is a great tool for fetching data over the network using a nice Promise-based API.
const endpoint = "https://jsonplaceholder.typicode.com/users";
fetch(endpoint).then(response => {
return response.json();
}).then(newUsers => {
newUsers.forEach(newUser => {
console.group(newUser.id);
console.log(newUser.email);
console.log(newUser.username);
console.groupEnd();
});
}).catch(error => {
console.error(error.message);
});
This code will fetch the users, display them, and account for network or syntax errors when needed. But this won't guarantee that the server has not changed the API between the years.
const endpoint = "https://jsonplaceholder.typicode.com/users";
fetch(endpoint).then(response => {
return response.json();
}).then(newUsers => {
const areNewUsersValid =
Array.isArray(newUsers)
&& newUsers.every(newUser => {
return typeof newUser === "object"
&& typeof newUser.id === "number"
&& typeof newUser.username === "string"
&& typeof newUser.email === "string";
});
if (!areNewUsersValid) {
return Promise.reject(new Error("Invalid data"));
}
newUsers.forEach(newUser => {
console.group(newUser.id);
console.log(newUser.email);
console.log(newUser.username);
console.groupEnd();
});
}).catch(error => {
console.error(error.message);
});
While this code does. Because we checked the structure of the data we received before. Now, we won't risk having a cannot read property id of undefined
kind of error when displaying informations.
Top comments (2)
Well, you wont in solution 1 either, but handling it with console error instead of an error component or modal is probably not preferred 👍
Correct, you should rather handle the error with a component or a modal (although a modal is not really great in a UX POV, I would rather suggest a toast notification instead which is less violent).
This
console.error
is here because I can't account for all possible frameworks, or components, or method etc... This is the part where you'll have to work a little bit to implement this solution in your own. 😉