CodeBlanks Logo Icon CodeBlanks

fetch

Learn HTTP requests with the fetch API.

What is the fetch API?

fetch is the standard way to make HTTP requests in the browser and React Native. It takes a URL and returns a Promise. The Promise represents the result of the request; when it resolves it gives the response.

Basic usage: fetch("https://api.example.com/users"). This call makes a GET request and returns a Promise. You wait for the Promise with .then() or with await. fetch is part of modern JavaScript; it needs no extra library. React Native also has alternatives like axios but fetch is enough for most cases. The Promise returned by fetch resolves when the response arrives; but it rejects on a network error.

Promise and then

fetch returns a Promise. You catch the Promise with .then(). The .then(response => ...) function runs when the response arrives. The response is a Response object; it does not hold the data directly, you call methods such as response.json() to extract it.

Example: fetch("https://api.example.com/users").then(response => response.json()).then(data => console.log(data));. The first then takes the response and turns it into JSON; the second then takes this JSON data. This chain structure lets you process asynchronous operations in order. Each then passes a value to the next one. The Promise chain is the basic way to write readable async code; but async/await makes it even cleaner.

Practice Make a request with fetch

Write a UserLoader component. Assign fetch("https://api.example.com/users") to a const promise. Add a promise.then(response => console.log(response)) call. The component returns null.

Starter code

App.js
// Call fetch (built in, no import needed)

function UserLoader() {
  // Make a request to the users address with fetch
  // Log the response with promise.then

  return null;
}

Sample solution

App.js
function UserLoader() {
  const promise = fetch("https://api.example.com/users");
  promise.then(response => console.log(response));
  return null;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What type does fetch return?

App.js
fetch("https://api.example.com/users");
  • Number
  • Array
  • String
  • Promise Correct answer

Explanation: answer: Promise. fetch's result is awaited with then or await.

2 Write the fetch call

Question
const url = "api.example.com/users";
const promise = ____(url);
Answer
const url = "api.example.com/users";
const promise = fetch(url);

Explanation: fetch takes a URL and makes a request.

3 Match the concept to its role

Term Meaning
fetch Makes an HTTP request
Promise Represents the result
then Catches the response
URL Request address

All lessons in Intermediate