DEV Community

victoriaehrbar
victoriaehrbar

Posted on

Fetch requests in JavaScript

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");
Enter fullscreen mode Exit fullscreen mode

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) => {

});
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

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);
  });
Enter fullscreen mode Exit fullscreen mode

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);
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)