๋ฌธ์ ๋ฐ์
๋ง์ด ํ์ด์ง ์ ์ ์ค, ์ฌ์ฉ์๊ฐ ์์ฑํ ๊ฒ์๊ธ์ ๋ถ๋ฌ์ค๊ธฐ ์ํด tanstackQuery ๋ฅผ ์ฌ์ฉํ์ฌ user์ ๋ณด์ post ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๋ ค๊ณ ํ์
usePostByUser(user.id)post๋ฅผ ์์ฒญํ ๋ user id๊ฐ ํ์ํด์ useSession์ผ๋ก ๋จผ์ user ์ ๋ณด๋ฅผ ๋ฐ๊ณ user.id๋ฅผ ๋ฃ์ผ๋ ค๊ณ ํ์๊ทธ๋ฐ๋ฐ
const {data: user} = useSession(); const {data: posts} = usePostByUser(user.id);์ด๋ ๊ฒ ํ๋๊น
Cannot read properties of undefined (reading 'getUser')์ค๋ฅ๊ฐ ๋ฐ์ํจ
user ๋ฐ์์ค๊ธฐ ์ ์ posts ์์ฒญ์ด ๊ฐ์ user๊ฐ ์๋ค๊ณ ๋์ด๊ทธ๋ผ user๊ฐ ์์ ๋๋ง posts ์์ฒญ์ ๋ฐ์์ผํ๋ ์ถ์ด์
const {data: user, isLoading, isError} = useSession(); if (!user || isLoading || isError) { return ; } const {data: posts} = usePostByUser(user.id);์ด๋ ๊ฒ ์์ ํ๋๋ ํด๋น ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค~
๋ฌธ์ ์์ธ
React๋ Hook์ด ํธ์ถ๋๋ ์์น๋ฅผ ์ค์ํ๊ฒ ์๊ฐํ๋๋ฐ, ๊ท์น์ ์ด๊ธธ ๊ฒฝ์ฐ ๋ฐ์ํ๋ ์ค๋ฅ์ ๋๋ค!์ค๋ฅ๊ฐ ๋ฐ์ํ๋ ๋ํ ์ํฉ
1. ์กฐ๊ฑด๋ถ๋ก Hooks ํธ์ถ
2. ๋ฐ๋ณต๋ฌธ ๋๋ ์ด๋ฒคํธ ํธ๋ค๋ฌ์์ Hooks ํธ์ถ
3. ์กฐ๊ฑด์ ๋ฐ๋ผ Hook ์ถ๊ฐ ๋ฐ ์ ๊ฑฐ๊ทธ๋ฌ๋๊น ๊ผญ ์ต์๋จ์ ๋๊ฐ๋ฅผ ์ฐ๋ฌ์ ๋ถ๋ฌ์ค๊ณ ์ฒ๋ฆฌํด์ผํ๋ค๋ ๋ง.
๋ฌธ์ ํด๊ฒฐ
์กฐ๊ฑด๋ฌธ์ ์ฌ์ฉํ์ง ์๊ณ user, post ์์ฒญ์ ์ฒ๋ฆฌํ ์ ์๋ ๋ฐฉ๋ฒ enabled, useEffect, ์์์์ ์์ฒญํ๊ณ props ๋ด๋ฆฌ๊ธฐ ๋ฑ ์ค์์ enabled ์ต์ ์ ์ถ๊ฐํ๋ ๊ฒ์ผ๋ก ํด๊ฒฐํ๋ค.export const usePostByUser = (userId: string | undefined) => { return useQuery({ queryKey: ["post", userId], queryFn: () => fetchPostByUser(userId), retry: 1, enabled: !!userId, // userId๊ฐ ์์ ๋๋ง ์์ฒญ ์คํ }); }; const { data: user } = useSession(); const { data: posts, isLoading } = usePostByUser(user?.id);