DEV Community

Cover image for Create custom fetch hook in react
Rajasekar Thangavel
Rajasekar Thangavel

Posted on • Edited on

1 1

Create custom fetch hook in react

Custom hook useFetch

import { useState, useEffect } from 'react';

const useFetch = (url, initialValue) => {
    const [data, setData] = useState(initialValue);
    const [error, setError] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        (async () => {
            try {
                const res = await fetch(url);
                const resJson = await res.json();
                setData(resJson);
            } catch (err) {
                setError(err);
            } finally {
                setLoading(false);
            }
        })();
    }, [url]);
    return { loading, data, error };
};

export default useFetch;
Enter fullscreen mode Exit fullscreen mode

usage

import useFetch from "./useFetch";
const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/todos', []);
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)