-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseFetch.ts
More file actions
27 lines (21 loc) · 715 Bytes
/
Copy pathuseFetch.ts
File metadata and controls
27 lines (21 loc) · 715 Bytes
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
import useSWR from 'swr';
import { useEffect, useState } from 'react';
const fetcher = (url: string) =>
fetch(url).then((res) => {
if (!res.ok) throw new Error('Failed to fetch');
return res.json();
});
const useFetch = (url: string | null, options?: any) => {
const { data, error, isValidating } = useSWR(url ? url : null, fetcher, {
...options,
});
const [isInitialLoad, setIsInitialLoad] = useState(true);
const isLoading = isInitialLoad || isValidating;
useEffect(() => {
if (!isValidating) {
setIsInitialLoad(false);
}
}, [isValidating]);
return { data, error, isLoading, isValidating };
};
export default useFetch;