T
TanStack3y ago
national-gold

use result from query without triggering a new query

I have the following scenario in a react native app: I have a component that queries for a list of restaurants and display them in a list. I have a filter button that when pressed displays a filter screen that shows the list of all cuisines: indian, chinese, etc. for the user to filter restaurants by. The list of cuisines is derived from the result of the restaurants query, so I want to use the result of the restaurants query. For example here is the first component:
function RestaurantsList() {
const { data } = useQuery(['restaurants], () =>
// fetching logic
)

// implement rendering
}
function RestaurantsList() {
const { data } = useQuery(['restaurants], () =>
// fetching logic
)

// implement rendering
}
and here is the second for example
function FilterScreen() {
const { data } = // this is the missing puzzle
const cuisines = data.map(restaurant => //filter logic )

// implement rendering
}
function FilterScreen() {
const { data } = // this is the missing puzzle
const cuisines = data.map(restaurant => //filter logic )

// implement rendering
}
However I do not want the FilterScreen to trigger the query again. I simply want to use the result. I also want it to be reactive, so that if data changed, the cuisines rerender with changed data. I think I can use staleTime: Infinity but I do want to the query to refetch when the RestaurantsList component unmounts and remounts.
2 Replies
frail-apricot
frail-apricot3y ago
Why not use useQuery again? It should return the data from the cache and it will be reactive. If you don't want it to trigger a background refetch, you can set the staleTime on the useQuery inside FilterScreen.
rising-crimson
rising-crimson3y ago
I agree, calling useQuery again is the way forward here IMO

Did you find this page helpful?