-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetch.js
33 lines (30 loc) · 826 Bytes
/
useFetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { useEffect, useState } from 'react'
const useFetch = (url = '', options = null) => {
const [data, setData] = useState(null)
const [error, setError] = useState(null)
const [isLoading, setIsLoading] = useState(false)
useEffect(() => {
let isMounted = true
setIsLoading(true)
//Replace Axios or any fetching library
fetch(url, options)
.then((res) => res.json())
.then((data) => {
if (isMounted) {
setData(data)
setError(null)
}
})
.catch((error) => {
if (isMounted) {
setError(error)
setData(null)
}
})
.finally(() => isMounted && setLoading(false))
//UnMounting
return () => (isMounted = false)
}, [url, options])
return { loading, error, data }
}
export default useFetch