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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

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