Answers for "useFetch custom hook for React"

0

React hook useFetch

import { useEffect, useState } from 'react';
    
export default function useFetch(url) {
    const [data, setData] = useState(null);
    useEffect(() => {
        async function loadData() {
            const response = await fetch(url);
            if(!response.ok) {
                // oups! something went wrong
                return;
            }
    
            const posts = await response.json();
            setData(posts);
        }
    
        loadData();
    }, [url]);
    return data;
}
Posted by: Guest on August-12-2021
0

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 };
};
Posted by: Guest on September-23-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language