medfouedslama
medfouedslama

Reputation: 235

react-query - How can I access my queries in multiple components?

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.

Upvotes: 17

Views: 31475

Answers (2)

Randall
Randall

Reputation: 2858

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"]);

Upvotes: 12

NearHuscarl
NearHuscarl

Reputation: 81833

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 (...)
}

Upvotes: 24

Related Questions