Skip to content

Commit 307d2b8

Browse files
committed
fix hydration error
1 parent 34394cc commit 307d2b8

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

web/components/search/table.tsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ export default function UserTable({ query }: { query: string }) {
99
const {
1010
state: { data },
1111
} = useAll();
12-
const { state } = useMyID();
12+
const {
13+
state: { data: myId },
14+
} = useMyID();
1315
const initialData = useMemo(() => {
14-
return (
15-
data?.filter((item) => item.id !== state.data && item.id !== 0) ?? null
16-
);
17-
}, [data, state.data]);
16+
return data?.filter((item) => item.id !== myId && item.id !== 0) ?? null;
17+
}, [data, myId]);
1818
const users = query
1919
? initialData?.filter((user) =>
2020
user.name.toLowerCase().includes(query.toLowerCase()),

web/hooks/useCustomizedSWR.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,17 @@ export function useCustomizedSWR<T>(
5151
): Hook<T> {
5252
const CACHE_KEY = SWR_PREFIX + cacheKey;
5353

54-
const [state, setState] = useState<State<T>>(() =>
55-
loadOldData(CACHE_KEY, schema),
56-
);
54+
// HACK: 最初の描画時の挙動をサーバー上の挙動とそろえるため、 useEffect() でstaleデータの読み込みを遅延している。
55+
// >> https://github.com/vercel/next.js/discussions/17443
56+
// >> Code that is only supposed to run in the browser should be executed inside useEffect. That's required because the first render should match the initial render of the server. If you manipulate that result it creates a mismatch and React won't be able to hydrate the page successfully.
57+
const [state, setState] = useState<State<T>>({
58+
current: "loading",
59+
data: null,
60+
error: null,
61+
});
62+
useEffect(() => {
63+
setState(loadOldData(CACHE_KEY, schema));
64+
}, [CACHE_KEY, schema]);
5765

5866
const reload = useCallback(async () => {
5967
setState((state) =>
@@ -151,5 +159,5 @@ function loadOldData<T>(
151159
}
152160

153161
function go(fn: () => Promise<void>) {
154-
fn();
162+
fn().catch(console.warn);
155163
}

0 commit comments

Comments
 (0)