Austin
Austin

Reputation: 351

Using a value from a previous query in react query

I have a react query to get user data like this

const { data: queryInfo, status: queryInfoLoading } = useQuery('users', () =>
    getUsers()),
  );

I then have a sibling component that needs the same data from the get users query. Is there a way to get the results of the get users query without re-running the query?

Essentially, I would like to do something like this

const userResults = dataFromUserQuery

const { data: newInfo, status: newInfoLoading } = useQuery('newUserData', () =>
        getNewUsers(userResults.name)),
      )

Upvotes: 1

Views: 7752

Answers (1)

TkDodo
TkDodo

Reputation: 28733

As suggested in this related question (how can i access my queries from react-query?), writing a custom hook and reusing it wherever you need the data is the recommended approach.

Per default, react-query will trigger a background refetch when a new subscriber mounts to keep the data in the cache up-to-date. You can set a staleTime on the query to tell the library how long some data is considered fresh. In that time, the data will always come from the cache if it exists and no refreshes will be triggered.

Upvotes: 1

Related Questions