Using react-query in external package leads to "No QueryClient set" error even though QueryClientProvider is used in index.js

Viewed 1149

I try to use hooks from an self developed package that uses useQuery within a create-react-app application.

This is my scenario: I am developing two npm projects: 'Core' and 'Demo'. Core contains functions, hooks and components that I'd like to use in other applications (like Demo which is a CRA). Some hooks contain useQuery (react-query). Unfortunately, when using this hooks in other applications like Demo, I always get the error message "No QueryClient set, use QueryClientProvider to set one" even though I set a QueryClientProvider.

Is there any configuration I have to set within Core to make the desired behaviour work (e.g. that the used hook is placed within the application context)? Do I have to build the package as a specific module? Or is it possible to pass the application's QueryClient to the custom hooks of Core?

Here's some code to show my attempt:

Core/hooks/useHookWithUseQuery.js

export function useHookWithUseQuery() {
  const queryClient = useQueryClient();
  const { data } = useQuery(
    "QUERY_KEY",
    getDataFn
  );

  const invalidateData = () => {
    queryClient.invalidateQueries("QUERY_KEY");
  };

  return { data, invalidateData };
}

Demo/index.js:

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient} contextSharing={false}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

Demo/App.js

import { useHookWithUseQuery } from "core/dist/hooks"; // also tried core/src/hooks
...

function App() {
  const { data } = useHookWithUseQuery();
 
  const { someFetchedText } = data;
  return (
    <div>{ someFetchedText }</div>
  );
}

And here is how I install Core into Demo

  • in Core (build + publish locally on Verdaccio)
    • rm -rf dist && NODE_ENV=production babel src --out-dir dist --copy-files
    • npm publish --registry http://localhost:4873/
  • in Demo
    • NPM_CONFIG_REGISTRY=http://localhost:4873 npm i core
1 Answers

I had the same problem and deduplicating your react-query dependency in your yarn lock or NPM package lock is the solution:

For yarn.lock you can run

npx yarn-deduplicate --strategy fewer

Or for package-lock.json:

npm dedupe

This will solve your issue like solved mine.

Related