Created
April 5, 2021 07:53
-
-
Save KRRISH96/e6e3f6524545bc29b47838215795e851 to your computer and use it in GitHub Desktop.
Simple useFetch react custom hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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