-
-
Save Vikaskumargd/1afdd1d4487d97f3f58d4ce72c1735a3 to your computer and use it in GitHub Desktop.
fetching data custom hook final version
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"; | |
export const useFetch = (url, ref, initialValue) => { | |
const [data, setData] = useState(initialValue); | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(true); | |
useEffect(() => { | |
if (ref.current) { | |
(async () => { | |
try { | |
const res = await fetch(url); | |
const resJson = await res.json(); | |
setData(resJson); | |
} catch (err) { | |
setError(err); | |
} finally { | |
setLoading(false); | |
} | |
})(); | |
} | |
return () => { | |
ref.current = false; | |
}; | |
}, [url, ref]); | |
return { loading, data, error }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment