17

I'm just beginning with react query and used it to get a list of books from the server using useQuery in my ListBooks Component

const { data, error, isLoading, isError } = useQuery("books", getAllBooks);

How can I access the list of books in any other component?

I've setted the QueryClientProvider like so :

 const queryCache = new QueryCache({
  onError: (error) => {
    console.log(error);
  },
});

const queryClient = new QueryClient({ queryCache });

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <ThemeProvider theme={preset}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </ThemeProvider>
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

I'm searching for the equivalent of useSelector in Redux to access the data in the redux store.

2 Answers 2

24

react-query manages query caching based on query keys, so in the other component, as long as they're all wrapped inside QueryClientProvider, you just need to call useQuery with the matching key (books), and react-query will return the appropriate data for you.

If you use the same query in multiple places, consider adding a wrapper hook to keep your code clean:

function useAllBooks() {
  return useQuery("books", getAllBooks)
}
function Component1() {
  const {...} = useAllBooks()
  return (...)
}

function Component2() {
  const {...} = useAllBooks()
  return (...)
}
Sign up to request clarification or add additional context in comments.

6 Comments

thanks for the quick response @NearHuscarl, so there isn't a "store" in react-query accessible from anywhere like in redux ?
By store, do you mean all cache data? @medfouedslama
@medfouedslama you can use queryClient.getQueryCache().queries. See this example.
thank you, that's what i was looking for.
please note that accessing the cache imperatively via the queryClient does NOT create a subscription, so your component will not be re-rendered if you use this during the render function, and it will also not trigger a fetch if the cache is empty. Only useQuery does that, so I'd recommend to always useQuery to read data from the cache.
|
13

You can get access with custom hook useGetFetchQuery and useQueryClient

import { useQueryClient } from "react-query";

export const useGetFetchQuery = (key) => {
    const queryClient = useQueryClient();

    return queryClient.getQueryData(key);
};

And in component just write like this

const data = useGetFetchQuery("key from useQuery or useMutation");

UPD

As correctly note @Tony Tai Nguyen with new (v5) release of react-query query keys should be an array.

const data = useGetFetchQuery(["query key"]);

4 Comments

This is the cleaniest approach to reach for allready fetched 'data'. But the variable 'data' is not reactive - That means that if the data is refetched/updated and so on - the 'data' variable will not update/ be updated... :( Is there a way to subscribe to data from a specific query?
this is returning undefined for me.
This function (useGetFetchQuery) will not update when query gets invalidated or udpated.
Note: if you are using the latest version of react query v5, you have to wrap the key around an array queryClient.getQueryData([key]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.