DEV Community

victoriaehrbar
victoriaehrbar

Posted on

2 2

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more