-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
50 lines (43 loc) · 1.27 KB
/
index.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
50
import React, {
Suspense,
useRef,
unstable_ConcurrentMode as ConcurrentMode,
} from 'react';
import ReactDOM from 'react-dom';
import { useFetch } from 'react-hooks-fetch';
// this can be too naive
const useMemoPrev = (create, inputs) => {
const memoized = useRef(null);
const prevInputs = useRef([]);
if (prevInputs.current.length !== inputs.length
|| prevInputs.current.some((x, i) => x !== inputs[i])) {
prevInputs.current = inputs;
memoized.current = create();
}
return memoized.current;
};
const Err = ({ error }) => <span>Error:{error.message}</span>;
const readBody = body => body.text();
const PostRemoteData = ({ userId, title, body }) => {
const opts = useMemoPrev(() => ({
method: 'POST',
body: JSON.stringify({
userId,
title,
body,
}),
readBody,
}), [userId, title, body]);
const { error, data } = useFetch('https://jsonplaceholder.typicode.com/posts', opts);
if (error) return <Err error={error} />;
if (!data) return null;
return <span>Result:{data}</span>;
};
const App = () => (
<ConcurrentMode>
<Suspense fallback={<span>Loading...</span>}>
<PostRemoteData userId={1} title="foo" body="bar" />
</Suspense>
</ConcurrentMode>
);
ReactDOM.render(<App />, document.getElementById('app'));