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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs