reactjsreact-nativereact-querytanstackreact-query

Tanstack-Query Caching Not Working When Calling fefetch


I'm using @tanstack/react-query in my React Native (Expo) & Firebase project. I have set everything necessary (such as QueryClientProvider). For an unknown reason chrome networking tab doesn't work in React Native project. For this reason, I added second line to determine if api is called. When I call refetch function the word "hello" is printed to console. I guess caching doesn't work properly. There is my code. 👇🏼

  const getData = async () => {
    console.log("hello") // This is my debug line

    const userId = authUser.uid
    const userResponse = await getUser(userId)
    const lastExamResultsResponse = await getLastExamResults(
      userId,
      LAST_EXAMS_COUNT
    )

    return {
      user: userResponse,
      lastExamResults: lastExamResultsResponse,
    }
  }

  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["user"],
    queryFn: getData,
  })

Where am I doing something wrong or how can I solve it?

I want to cache my data properly. refetch function must use cached data when there is data in cache. But it doesn't work.


Solution

  • The refetch function does the same as invalidateQuery. it's not a getter its trigger. You can access the cached data from "data" that returend useQuery(). if you want to access cached data from other components. use useQuery with same key and you will be able to access cached data. with {data}=useQuery another option is queryClient.getQueryData(['user']) will also return cached data.