Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

useFetch custom hook for React

import { useEffect, useState } from 'react';

const useFetch = (url) => {
	const [data, setData] = useState(null);
	const [isLoading, setIsLoading] = useState(true);
	const [error, setError] = useState(null);

	useEffect(() => {
		const abortCont = new AbortController();

		fetch(url, { signal: abortCont.signal })
			.then((res) => {
				if (!res.ok) {
					throw Error('Could not fetch the data for that resource');
				}
				return res.json();
			})
			.then((data) => {
				setData(data);
				setIsLoading(false);
				setError(null);
			})
			.catch((err) => {
				if (err.name === 'AbortError') {
					console.log('Fetch aborted');
				} else {
					setError(err.message);
					setIsLoading(false);
				}
			});
		return () => abortCont.abort();
	}, [url]);
	return { data, isLoading, error };
};
Comment

basic useFetch custom hook

const useFetch = (url) => {
    const [status, setStatus] = useState('idle');
    const [data, setData] = useState([]);

    useEffect(() => {
        if (!url) return;
        const fetchData = async () => {
            setStatus('fetching');
            const response = await fetch(url);
            const data = await response.json();
            setData(data);
            setStatus('fetched');
        };

        fetchData();
    }, [url]);

    return { status, data };
};
Comment

PREVIOUS NEXT
Code Example
Javascript :: An accessor cannot be declared in an ambient context. 
Javascript :: getting data from firestore using async await 
Javascript :: matrix elements sum javascript 
Javascript :: express draft 
Javascript :: javascript get name of element 
Javascript :: toobject() javascript 
Javascript :: placeholder in angular 9 select with working required 
Javascript :: replace current uri react router 
Javascript :: electron download 
Javascript :: vue.js cdn 
Javascript :: js computed style 
Javascript :: iframe in angular 
Javascript :: loopback get relationship in before save 
Javascript :: Nazmul 
Javascript :: Get child node index 
Javascript :: javascript check if not null 
Javascript :: jsx if block 
Javascript :: javascript alphabet to number 
Javascript :: fetch data from api in react 
Javascript :: How to know react and react-native version 
Javascript :: instantiate object in script godot 
Javascript :: node js request download file 
Javascript :: change list of objects to list js 
Javascript :: javascript css left 
Javascript :: redirect the page in javascript 
Javascript :: js replace all substrings 
Javascript :: java superscript numbers 
Javascript :: jquery get document scrolltop 
Javascript :: jquery load event 
Javascript :: ExpressionChangedAfterItHasBeenCheckedError: 
ADD CONTENT
Topic
Content
Source link
Name
7+6 =