Avoid Provider nesting

I am going to have a lot of Providers in my App, and i did not want to have 5+ nesting around my rotes. Here is the example with just 2 providers:
return (
<ErrorBoundary fallback={(err, reset) => <div onClick={reset}>Error: {err.toString()}</div>}>
<PortfolioProvider>
<UserProvider>
<Routes>
<Route path="/" element={PageLayout}>
<Route path="/" element={<h1>Home</h1>} />
<Route path="/about" element={<h1>About</h1>} />
<Route path="/users" element={<h1>Users</h1>} />
<Route path="/signin" element={SignIn} />
</Route>
</Routes>
</UserProvider>
</PortfolioProvider>
</ErrorBoundary>
);
return (
<ErrorBoundary fallback={(err, reset) => <div onClick={reset}>Error: {err.toString()}</div>}>
<PortfolioProvider>
<UserProvider>
<Routes>
<Route path="/" element={PageLayout}>
<Route path="/" element={<h1>Home</h1>} />
<Route path="/about" element={<h1>About</h1>} />
<Route path="/users" element={<h1>Users</h1>} />
<Route path="/signin" element={SignIn} />
</Route>
</Routes>
</UserProvider>
</PortfolioProvider>
</ErrorBoundary>
);
So i though i could put all my providers into to a single component, and then only have 1 "Provider" around my Routes. However when i do this, i can see from logging that my providers are created, but non of the sub-components have assess to the useUser or useProtfolios as they are undefined. This works fine when i have the providers around my rote but not when i wrap them in a component. Should the following not work?
import { JSX } from "solid-js";
import { UserProvider } from "./contexts/userContext";
import { PortfolioProvider } from "./contexts/portfolioContext";

interface ProviderProps {
children: JSX.Element;
}

const AppProviders = ({ children }: ProviderProps) => {
console.log("Adding context providers");
return (
<UserProvider>
<PortfolioProvider>{children}</PortfolioProvider>
</UserProvider>
);
};

export default AppProviders;
import { JSX } from "solid-js";
import { UserProvider } from "./contexts/userContext";
import { PortfolioProvider } from "./contexts/portfolioContext";

interface ProviderProps {
children: JSX.Element;
}

const AppProviders = ({ children }: ProviderProps) => {
console.log("Adding context providers");
return (
<UserProvider>
<PortfolioProvider>{children}</PortfolioProvider>
</UserProvider>
);
};

export default AppProviders;
App.tsx i replace the 2 providers with <AppProviders>...</AppProviders>
2 Replies
REEEEE
REEEEE2y ago
don't destructure the props
const AppProviders = (props: ProviderProps) => {
console.log("Adding context providers");
return (
<UserProvider>
<PortfolioProvider>{props.children}</PortfolioProvider>
</UserProvider>
);
};
const AppProviders = (props: ProviderProps) => {
console.log("Adding context providers");
return (
<UserProvider>
<PortfolioProvider>{props.children}</PortfolioProvider>
</UserProvider>
);
};
Kasper
KasperOP2y ago
Thanks
Want results from more Discord servers?
Add your server