Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading