Chain 2 queries in RTK Query
Asked Answered
C

4

20

What is the proper way to chain queries if the 2nd query requires a parameter that is returned by the 1st?

const { data: user } = useGetUserQuery();

The user object contains an ID that is used to run

const { data: userBio} = useGetUserBioQuery(user.id);

How do I make sure the 2nd one runs only after the 1st one is fulfilled?

Counterstamp answered 9/10, 2021 at 8:40 Comment(0)
B
23

You can use the skip option:

const { data: user, isFulfilled: userFulfilled } = useGetUserQuery();
const { data: userBio} = useGetUserBioQuery(user.id, { skip: !userFulfilled });

Or a skipToken:

import { skipToken } from '@reduxjs/toolkit/query/react'

const { data: user, isFulfilled: userFulfilled } = useGetUserQuery();
const { data: userBio} = useGetUserBioQuery(userFulfilled ? user.id : skipToken);
Branham answered 9/10, 2021 at 9:29 Comment(2)
I tried it but Typescript doesn't seem to be happy with it. Is there a better way than just shut it down with the non-null assertion operator?Counterstamp
the skipToken approach, but no destructuring of your result variable. that will keep the correlation isFulfilled => data is not undefinedBranham
F
6

The usage section of the RTK Query docs also provides another example on how to combine multiple requests with one single query that I found very usefull for that use case: https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#performing-multiple-requests-with-a-single-query

Frendel answered 17/1, 2022 at 15:17 Comment(0)
W
4

we can use skip flag to make sure if there is user id

const { data: user } = useGetUserQuery();
const { data: userBio} = useGetUserBioQuery(user.id, { skip: !user.id });
Woeful answered 9/1, 2023 at 15:48 Comment(0)
B
0

Simplifying the accepted reponse on the use of skipToken. I simply use the ?? operator to use the defined previous response or skip the query.

import { skipToken } from '@reduxjs/toolkit/query/react'

const { data: user } = useGetUserQuery();
const { data: userBio } = useGetUserBioQuery(user.id ?? skipToken);
Briannebriano answered 9/5 at 0:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.