Skip to content

Instantly share code, notes, and snippets.

@KRRISH96
Created April 5, 2021 07:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save KRRISH96/e6e3f6524545bc29b47838215795e851 to your computer and use it in GitHub Desktop.
Simple useFetch react custom hook
import { useState, useEffect } from 'react';
const API_BASE_URL = 'https://jsonplaceholder.typicode.com'; // Ex: API link, replace with required API URL
/**
* @param endpoint endpoint to fetch data from
* @returns { data, error, loading }
*/
export function useFetch(endpoint){
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let didCancelFetch = false;
// Resets the loader and errors on subsequent calls
setError(null);
setLoading(true);
const fetchData = async () => {
try {
if (!didCancelFetch) {
const res = await fetch(`${API_BASE_URL}${endpoint}`);
const responseJson = await res.json();
setData(responseJson);
}
} catch (err) {
setError(err.message || 'Something went wrong!');
}
setLoading(false);
};
fetchData();
return () => {
didCancelFetch = true;
};
}, [endpoint]);
return { data, error, loading };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment