CodeBlanks Logo Icon CodeBlanks

Summary - API and fetch

Combine fetch, async/await and error handling to write a user viewer.

Summary - API and fetch

In this group you learned fetch, GET, async/await, JSON parse and error handling. fetch takes a URL, makes an HTTP request and returns a Promise. GET is fetch's default method.

With async/await you simplify the then chain; you define and call an async function inside useEffect. response.json() parses the response and turns it into a JavaScript object. You catch errors with try/catch; for HTTP errors you check response.ok. Now you will combine all of this into a working user viewer. The component will make an API call when it mounts, put the data into state and show it on screen. If there is an error it will show a message to the user.

Practice Write the user state

Write a UserViewer component. Start user state with null, loading state with true, error state with null using useState.

Starter code

App.js
// Import useState and Text, View

function UserViewer() {
  // Start user, loading and error state

  return null;
}

Sample solution

App.js
import { useState } from "react";
import { Text, View } from "react-native";

function UserViewer() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  return null;
}

Practice Add the data loading

Write a UserViewer component. Start user, loading, error state with useState. Inside useEffect define an async function load. The load function: assign await fetch("https://api.example.com/users/1") to const response, assign await response.json() to const data, call setUser(data). In a catch (error) block call setError(error.message). Finally call setLoading(false). Use the empty dependency array [].

Starter code

App.js
// Import useState, useEffect and Text, View

function UserViewer() {
  // Start user, loading, error state
  // Define async load inside useEffect and call it

  return null;
}

Sample solution

App.js
import { useEffect, useState } from "react";
import { Text, View } from "react-native";

function UserViewer() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    async function load() {
      try {
        const response = await fetch("https://api.example.com/users/1");
        const data = await response.json();
        setUser(data);
      } catch (error) {
        setError(error.message);
      } finally {
        setLoading(false);
      }
    }
    load();
  }, []);
  return null;
}

Questions and answers

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

1 When is the data loaded in the user viewer?

App.js
useEffect(() => { /* ... */ }, []);
  • Once, when the component appears Correct answer
  • Only when the button is pressed
  • Her render'da
  • Never

Explanation: With the empty dependency array useEffect runs once when the component mounts.

2 Write the JSON parse call

Question
const data = await ____;
Answer
const data = await response.json();

Explanation: response.json() parses the response.

3 Match the concept to its role

Term Meaning
fetch Makes a request
await Waits for a Promise
response.json() Parses JSON
try/catch Catches errors

All lessons in Intermediate