Search code examples
reactjstypescriptreact-nativereact-querytanstackreact-query

Access React Query / Tan Stack Query cached data from outside the react tree?


I am working on an error handler for the whole mobile app. So when an unexpected error occurs, it sends user data to server.

I used to have a global state, so getting user infos from there was easy, but since I removed user global state and replaced it directly with my backend react query request, I am not sure how to get the user data from the cache here since I can't use a react hook (useSomething...) outside of the react tree.

I have tried queryCache.find({ queryKey: ['userGetOne'] }) from this doc but it returns undefined, eventhough I'm sure my queryKey match a defined request. Also this don't seem the recommended way to go.

I can provide more code examples if needed but I'm not sure it will be relevant here.


Solution

  • You can access the data through the queryClient (the same one that you passed into <QueryClientProvider>):

    // In your main app file
    export const queryClient = new QueryClient(/* ... options */);
    
    const App = () => {
      return (
        <QueryClientProvider client={queryClient}>
         {/* other elements */}
        </QueryClientProvider>
      )
    }
    
    // Elsewhere:
    import { queryClient } from '[yourMainAppFile]'
    
    function onError() {
      const value = queryClient.getQueryData(['userGetOne']);
      console.log('error!', value);
    }