Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain 2 queries in RTK Query

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?

like image 328
Oleksandr Fomin Avatar asked Nov 21 '25 17:11

Oleksandr Fomin


2 Answers

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);
like image 68
phry Avatar answered Nov 23 '25 07:11

phry


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

like image 42
BenJey Avatar answered Nov 23 '25 06:11

BenJey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!