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
demo
andcore
each come with their own version of React (and/or react-query) bundled? Because that might be the reason that context cannot be shared between them. – Shirleycore
I set React as peer dependency:"peerDependencies": { "react": "^17.0.2", ...}
. Indemo
it's just a dependency:"dependencies": { "react": "^17.0.2", ... }
I had problems with using React in two packages when I just added thecore
this way:npm i local/path/to/core
and could solve the issue by linking the React versionnpm link path/to/core/node_modules/react
. Later on I discovered Verdaccio and figured out that I do not have linking issues when I just publishcore
, locally. – Olssonreact-query
module. Normally, react context Provider and Consumer must be referring to the same exact instance of the Context for it to work. For that those two must be imported from the same exact ES module (not just the same version). So, using it as a peer dependency and deduping should have helped. – Ultramicroscope