-
Notifications
You must be signed in to change notification settings - Fork 1
/
useSWR.js
49 lines (36 loc) · 1.02 KB
/
useSWR.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
SWR is a popular library of data fetching.
Let's try to implement the basic usage by ourselves.
```
import React from 'react'
function App() {
const { data, error } = useSWR('/api', fetcher)
if (error) return <div>failed</div>
if (!data) return <div>loading</div>
return <div>succeeded</div>
}
```
1. This is not to replicate the true implementation of useSWR()
2. The first argument key is for deduplication, we can safely ignore it for now
*/
import { useEffect, useState } from "react";
export const useSWR = (fetcher) => {
const [data, setData] = useState();
const [error, setError] = useState();
const result = fetcher();
const fetcherReturnedPromise = result instanceof Promise;
const fetchData = async () => {
try {
const response = await fetcher();
setData(response);
} catch (error) {
setError(error);
}
};
useEffect(() => {
if (fetcherReturnedPromise) {
fetchData();
}
}, []);
return { data: fetcherReturnedPromise ? data : result, error };
};