Dependent Queries(์์กด์ฑ ์ฟผ๋ฆฌ)
1. useQuery dependent Query
Dependent (or serial) query
์์กด์ (๋๋ ์ง๋ ฌ) query๋ ์ด์ query๊ฐ ์คํ๋๊ธฐ ์ ์ ์๋ฃ๋์ด์ผ ํฉ๋๋ค.
์ด๋ฅผ ๋ฌ์ฑํ๊ธฐ ์ํด์๋ enabled ์ต์
์ ์ฌ์ฉํ์ฌ, query๊ฐ ์คํ ์ค๋น๊ฐ ๋์์ ๋๋ฅผ ์๋ ค์ฃผ๋ฉด ๋ฉ๋๋ค.
1// Get the user2const { data: user } = useQuery({3queryKey: ['user', email],4queryFn: getUserByEmail,5})67const userId = user?.id89// Then get the user's projects10const {11status,12fetchStatus,13data: projects,14} = useQuery({15queryKey: ['projects', userId],16queryFn: getProjectsByUser,17// The query will not execute until the userId exists18enabled: !!userId,19})
projects query๋ ๋ค์์์ ์์๋ฉ๋๋ค:
1status: 'pending'2isPending: true3fetchStatus: 'idle'
์ฌ์ฉ์๊ฐ ์ฌ์ฉ ๊ฐ๋ฅํด์ง๋ ์ฆ์, projects query๊ฐ enabled(ํ์ฑํ)๋๊ณ ๊ทธ ํ์ ๋ค์์ผ๋ก ์ ํ๋ฉ๋๋ค:
1status: 'pending'2isPending: true3fetchStatus: 'fetching'
ํ๋ก์ ํธ๊ฐ ์ค๋น๋๋ฉด, ๋ค์๊ณผ ๊ฐ์ด ์ด๋ํฉ๋๋ค.
1status: 'success'2isPending: false3fetchStatus: 'idle'
2. useQuery ์ข ์ ์ฟผ๋ฆฌ
๋์ parallel query - useQueries์ ์์กดํ ์๋ ์์ผ๋ฉฐ, ์ด๋ฅผ ๋ฌ์ฑํ๋ ๋ฐฉ๋ฒ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
1// Get the users ids2const { data: userIds } = useQuery({3queryKey: ['users'],4queryFn: getUsersData,5select: users => users.map(user => user.id),6})78// Then get the users messages9const usersMessages = useQueries({10queries: userIds11? userIds.map(id => {12return {13queryKey: ['messages', id],14queryFn: () => getMessagesByUsers(id),15}16})17: [], // if users is undefined, an empty array will be returned18})
์ฐธ๊ณ ์ฌํญ : useQueries๋ query ๊ฒฐ๊ณผ์ ๋ฐฐ์ด์ ๋ฐํํฉ๋๋ค.
3. ์ฑ๋ฅ์ ๋ํ ์ฐธ๊ณ ์ฌํญ
์์กด์ query๋ ์ ์์ ์์ฒญ ํญํฌ, request-waterfalls๋ฅผ ํ์ฑํ๋ฉฐ, ์ฑ๋ฅ์ ํด๋ฅผ ๋ผ์นฉ๋๋ค.
๋ query๊ฐ ๊ฐ์ ์๊ฐ์ด ๊ฑธ๋ฆฐ๋ค๊ณ ๊ฐ์ ํ ๋, ๋ณ๋ ฌ๋ก ์คํํ๋ ๋์ ์ง๋ ฌ๋ก ์คํํ๋ฉด ํญ์ ๋ ๋ฐฐ์ ์๊ฐ์ด ๊ฑธ๋ฆฝ๋๋ค.
์ด๋ ํนํ ์ง์ฐ ์๊ฐ์ด ๊ธด ํด๋ผ์ด์ธํธ์์ ๋ฐ์ํ ๋ ํนํ ํด๋ก์ธ ์ ์์ต๋๋ค.
๊ฐ๋ฅํ๋ค๋ฉด ํญ์ ๋ query๋ฅผ ๋ณ๋ ฌ๋ก ๊ฐ์ ธ์ฌ ์ ์๋๋ก ๋ฐฑ์๋ API๋ฅผ ์ฌ๊ตฌ์ฑํ๋ ๊ฒ์ด ์ข์ง๋ง,
ํญ์ ์ค์ฉ์ ์ผ๋ก ๊ฐ๋ฅํ ๊ฒ์ ์๋ ์ ์์ต๋๋ค.
์์ ์์์์ getUserByEmail์ ๋จผ์ ๊ฐ์ ธ์์ getProjectsByUser๋ฅผ ๊ฐ์ ธ์ค๋ ๋์ ์,
์๋ก์ด getProjectsByUserEmail ์ฟผ๋ฆฌ๋ฅผ ๋์
ํ๋ฉด, ์์ฒญ ํญํฌ(waterfall)๋ฅผ ํํํ๊ฒ ๋ง๋ค ์ ์์ต๋๋ค.