diff --git a/README.md b/README.md index 320efbf..7cb8e9a 100644 --- a/README.md +++ b/README.md @@ -3,3 +3,11 @@ # custom-hooks A collection of some cool custom hooks + +### `useArrayRef` - [View code](https://github.com/ashish-r/custom-hooks/blob/master/hooks/useArrayRef.js) + +### `useMountEffect` - [View code](https://github.com/ashish-r/custom-hooks/blob/master/hooks/useMountEffect.js) + +### `useOnClickOutside` - [View code](https://github.com/ashish-r/custom-hooks/blob/master/hooks/useOnClickOutside.js) + +### `usePrevious.js` - [View code](https://github.com/ashish-r/custom-hooks/blob/master/hooks/usePrevious.js) diff --git a/hooks/useFetch.js b/hooks/useFetch.js new file mode 100644 index 0000000..9916911 --- /dev/null +++ b/hooks/useFetch.js @@ -0,0 +1,27 @@ +import { useState, useEffect } from "react"; + +const useFetch = url => { + const [error, setError] = useState(); + const [loading, setLoading] = useState(false); + const [response, setResponse] = useState(); + + useEffect(() => { + const fetchInfo = async () => { + setLoading(true); + try { + const response = await fetch(url); + const result = await response.json(); + setResponse(result); + } catch (error) { + setError(error); + } + setLoading(false); + }; + + fetchInfo(); + }, [url]); + + return { error, loading, response }; +}; + +export default useFetch; \ No newline at end of file