-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPageWrapper.tsx
51 lines (45 loc) · 1.46 KB
/
PageWrapper.tsx
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
51
import axios from "axios";
import React, { useEffect, useRef, useState, VFC } from "react";
import { useLocation } from "react-router-dom";
type Props = {
serverData?: any;
PageComponent: VFC<{ data?: any; isLoading: boolean }>;
};
const PageWrapper: VFC<Props> = ({ serverData, PageComponent }) => {
const [data, setData] = useState(() => {
if (typeof document !== "undefined") {
const dataPool = (document.getElementById("root") as HTMLElement).dataset
.react;
const unsafeData = dataPool ? JSON.parse(dataPool) : null;
(document.getElementById("root") as HTMLElement).dataset.react = "";
return unsafeData;
} else {
return serverData; // SSRしてる時
}
});
const [isLoading, setIsLoading] = useState(data ? false : true);
const { pathname } = useLocation();
const shouldFetch = useRef(!data);
useEffect(() => {
if (shouldFetch.current) {
const f = async () => {
setIsLoading(true);
const result = await axios
.get(`/api${window.location.pathname}`)
.then((data) => data.data)
.catch((error) => {
console.warn(error);
return null;
});
setData(result);
setIsLoading(false);
shouldFetch.current = false;
};
f();
} else {
shouldFetch.current = true;
}
}, [pathname, shouldFetch]);
return <PageComponent data={data} isLoading={isLoading} />;
};
export default PageWrapper;