React Native
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.
Exercise Write the user state
Write a UserViewer component. Start user state with null, loading state with true, error state with null using useState.
Show example solution
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;
}
Exercise 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 [].
Show example solution
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;
}
Test yourself
-
When is the data loaded in the user viewer?
useEffect(() => { /* ... */ }, []);
- Once, when the component appears
- Only when the button is pressed
- Her render'da
- Never
Show answer
Once, when the component appears — With the empty dependency array useEffect runs once when the component mounts.
-
Write the JSON parse call
const data = await ____;
Show answer
const data = await response.json();
-
Match the concept to its role
- fetch
- Makes a request
- await
- Waits for a Promise
- response.json()
- Parses JSON
- try/catch
- Catches errors
Next lesson: Quiz model