How to use data from last query as argument for next call of the same query with RTK Query?

Viewed 29

I'm moving from plain redux thunks to RTK query and I've run into a problem. After first query, the response contains a field with a value (kinda token or cursor) and I need to use it as argument in the next fetch of the same query and so on. With plain thunks I just read the token value from the store with a selector and use it as an argument

Something like this, but of course it causes an error:

const { data } = useUsersQuery({
  someToken: data.someToken,
});

How can I achieve it?

UPDATE I solved it with useLazyQuery():

const [trigger, { data }] = useLazyUsersQuery();

trigger({
  someToken: data?.someToken,
});

It looks ugly, though

1 Answers

You can just use skipToken or the skip option:

const { data } = useUsersQuery({
  someToken: firstResult.data.someToken,
}, {
  skip: !firstResult.isSuccess
});

or

const { data } = useUsersQuery(firstResult.isSuccess ? {
  someToken: firstResult.data.someToken,
} : skipToken);
Related