Most of the time in your applications, you will need to access data, or "fetch" it from another source, such as a server, API, etc.
This is where fetch requests come in handy.
I'll use this free API about dogs for dummy data.
A fetch request starts out looking like this:
fetch("https://dog.ceo/api/breeds/image/random");
All this does is request the data though; we need some kind of response so we can actually see this data.
fetch("https://dog.ceo/api/breeds/image/random").then((response) => {
});
The response object needs to be translated into a JSON so we are able to use it.
fetch("https://dog.ceo/api/breeds/image/random").then((response) => {
return response.json();
});
Since the json() method also returns a promise, let's return that promise and use another then().
fetch("https://dog.ceo/api/breeds/image/random")
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json);
});
Don't forget to add a catch() method at the end of the series of then() methods to catch any errors for unsuccessful requests.
fetch("https://dog.ceo/api/breeds/image/random")
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json);
})
.catch((err) => {
console.log(err);
});
Top comments (0)