I want to use a single Wrapper Component in a library im providing. The wrapper should provide stuff like Context and QueryClient. The component looks like this:
JavaScript
x
12
12
1
import { QueryClient, QueryClientProvider } from "react-query";
2
3
const client = new QueryClient();
4
5
function Wrapper(props) {
6
return (
7
<QueryClientProvider client={client}>
8
{props.children}
9
</QueryClientProvider>
10
);
11
}
12
When wrapping children with the Wrapper
useQuery throws an error that no QueryClientProvider is set. In this case App
uses the useQuery Hook from react-query.
JavaScript
1
11
11
1
import { Wrapper } from "my-lib";
2
3
ReactDOM.render(
4
<React.StrictMode>
5
<Wrapper>
6
<App />
7
</Wrapper>
8
</React.StrictMode>,
9
document.getElementById("root")
10
);
11
At first i thought you need a QueryClientProvider directly above an useQuery hook. But for example in Storybook you can define one QueryClient for all stories together. Where did i went wrong?
Edit: App component:
JavaScript
1
12
12
1
import { useQuery } from "react-query";
2
3
export const App = () => {
4
const data = useQuery("data", () =>
5
fetch("https://jsonplaceholder.typicode.com/todos/1").then((res) =>
6
res.json()
7
)
8
);
9
if (data.isError || data.isLoading) return <>Error/Loading</>;
10
return <>{data.data.title}</>;
11
};
12
Advertisement
Answer
Well a few steps lead to my goal:
- In the library, put
react-query
into thedevDependencies
andpeerDependencies
. - In the app, put
react-query
into thedependencies
. - In the library, exclude
react-query
from being bundled by adding it to your bundler config. In my case it’s thevite.config.ts
:
JavaScript
1
22
22
1
const path = require("path");
2
const { defineConfig } = require("vite");
3
4
module.exports = defineConfig({
5
build: {
6
lib: {
7
entry: path.resolve(__dirname, "src/index.ts"),
8
name: "my-lib",
9
formats: ["es", "umd"],
10
fileName: "my-lib",
11
},
12
rollupOptions: {
13
external: [
14
"react",
15
"react-dom",
16
"react-query",
17
],
18
},
19
},
20
});
21
22