Module Federation and QueryClientProvider
Is there a pattern for using a single QueryClient when using module federation?
I have a host app and a few sub applications:
host
|- app1
|- app2
host, app1 and app2 make API requests but I want to use the same QueryClient between them.
In my host app I'm creating the query client and wrapping everything, including the React Router
Outlet that serves the federated modules with my QueryClientProvider but when making calls from the sub applications it errors out saying there is no QueryClientProvider available. Wrapping the sub applications with QueryClientProvider resolves this but creates an additional QueryClient which I'd like to avoid so there can be a single client/cache.6 Replies
manual-pink•3y ago
You can wrap each app in its own
<QueryClientProvider> but still give them the same QueryClient instance. Not sure how to share that instance amongst the different app though. A naive implementation (which works still) would be to store the query client on the window, but there might be better ways to do so in the module federation tools you're using.ratty-blushOP•3y ago
I may be able to expose the client through a shared library as a singleton. I'll try that out.
vicious-gold•3y ago
You should be able to use a singleton query client instance across multiple providers as far as I know 👍
foreign-sapphire•3y ago
Thanks for linking here @julien. Good stuff, though
<QueryClientProvider client={window.parent.queryClient}> makes me feel like uneasy haha.foreign-sapphire•3y ago

manual-pink•3y ago
Could be an issue when using the page outside of iframe (
window.parent would be undefined). So you could have a fallback : const queryClient = window.parent.queryClient ?? new QueryClient().