Created
April 8, 2020 02:59
-
-
Save Dromediansk/a308da027d4e0daedb032df98b89a7bc 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