usefetch custom hook for react

Solutions on MaxInterview for usefetch custom hook for react by the best coders in the world

showing results for - "usefetch custom hook for react"
Marlene
10 Jun 2020
1import { useEffect, useState } from 'react';
2    
3export default function useFetch(url) {
4    const [data, setData] = useState(null);
5    useEffect(() => {
6        async function loadData() {
7            const response = await fetch(url);
8            if(!response.ok) {
9                // oups! something went wrong
10                return;
11            }
12    
13            const posts = await response.json();
14            setData(posts);
15        }
16    
17        loadData();
18    }, [url]);
19    return data;
20}
21
Grace
22 Mar 2017
1import { useEffect, useState } from 'react';
2
3const useFetch = (url) => {
4	const [data, setData] = useState(null);
5	const [isLoading, setIsLoading] = useState(true);
6	const [error, setError] = useState(null);
7
8	useEffect(() => {
9		const abortCont = new AbortController();
10
11		fetch(url, { signal: abortCont.signal })
12			.then((res) => {
13				if (!res.ok) {
14					throw Error('Could not fetch the data for that resource');
15				}
16				return res.json();
17			})
18			.then((data) => {
19				setData(data);
20				setIsLoading(false);
21				setError(null);
22			})
23			.catch((err) => {
24				if (err.name === 'AbortError') {
25					console.log('Fetch aborted');
26				} else {
27					setError(err.message);
28					setIsLoading(false);
29				}
30			});
31		return () => abortCont.abort();
32	}, [url]);
33	return { data, isLoading, error };
34};