CodeBlanks Logo Icon CodeBlanks

Challenge: useFetch hook

Write a useFetch hook that returns loading, error and data states.

Challenge: useFetch hook

In this challenge you write a useFetch hook. It takes a URL, fetches the data, and returns { data, error, loading }.

Hint: call fetch inside useEffect; keep loading and data in useState. On error, set error.

This challenge comes with few hints; combine what you have learned.

Practice Write useFetch hook

Write a useFetch hook: take a url parameter, keep data (null), loading (true) and error (null) in useState. Inside useEffect, call fetch(url), parse JSON with .then(r => r.json()), set data with .then(setData), set error with .catch(setError), and set loading false with .finally(() => setLoading(false)). Return { data, loading, error } and export. The useEffect dependency array should be [url].

Starter code

App.jsx
import { useState, useEffect } from "react";

// useFetch hook'unu buraya yaz

Sample solution

App.jsx
import { useState, useEffect } from "react";

export function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    fetch(url)
      .then((r) => r.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);
  return { data, loading, error };
}

Questions and answers

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

1 What should useFetch return?

  • Only data
  • Data, error and loading Correct answer
  • Only loading
  • Only error

Explanation: { data, error, loading } are the hook's three states.

2 useFetch loading state

Question
export function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(____);
  const [error, setError] = useState(null);
  useEffect(() => {
    fetch(url).then(r => r.json()).then(setData).finally(() => setLoading(false));
  }, [url]);
  return { data, loading, error };
}
Answer
export function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    fetch(url).then(r => r.json()).then(setData).finally(() => setLoading(false));
  }, [url]);
  return { data, loading, error };
}

Explanation: Loading starts as true.

All lessons in Intermediate