0
votes

I am using react-query in my project and it works great

I wonder if react-query has a selector feature. I use react-query to fetch a list of posts, for example, and would like to filter only the completed post. I want to cache the filter result so the next time I filter the list again, it can return the cache. Basically, the feature I want is the same as selectors in recoil

2

2 Answers

0
votes

It's important to have in mind that react-query does not provide a local state. All fetched data is a temporary representation (cache) of the server state. It implements the SWR (stale-while-revalidate) pattern.

Although you can achieve what you want by selecting the data from the cache provided by react-query(you need to do it yourself, there are no selectors) it might be tricky if you use pagination or if you data becomes stale immediately (default lib behaviour).

So assuming your data is a temporary representation of server state it would be better to include the filters in the query key so you would end up making different queries and having different independent cache entries to different filter combinations. This way:

  • You don't need selectors
  • You only fetch what you need
  • When you change the filters you have access to the cache data (if any) while react-query refetches in the background. This depends on how you configure react-query
0
votes

I am not aware of a builtin native selector solution, but You can achieve this with a custom hook.

function useMostPopularPosts(){
  const postsResult = useQuery(postsQueryParams)
  const mostPopularResult = useQuery(popularPostsQueryParams)

  if (!(postsResult.success && mostPopularResult.success)){
    return []; 
  }

  return postsResult.data.filter(
    post=> mostPopularResult.data.includes(post.id)
  )

 
}

function MostPopularPosts(){
  const popularPosts = usePopularPosts()

  return <>
    {
      popularPosts.map(post=>(
        <PostHighlight post={post} />
      ))
    }
  </>
}