-
So I needed to use contexts for one of my projects and using the tutorial I started working on this. However calling useContext in a child component results in Here's how my code is laid out: ...
render(
() => (
<Router>
<App />
</Router>
),
document.getElementById("root") as HTMLElement
); App.tsx ...
import { DiscordProvider } from "./lib/discord/provider";
import { HomePage } from "./pages/Home";
const App: Component = () => {
return (
<DiscordProvider>
<HomePage />
</DiscordProvider>
);
};
export default App; provider.tsx export const DiscordContext = createContext<ContextProps>();
export const DiscordProvider: Component = ({ children }) => {
...
return (
<DiscordContext.Provider
value={{
authorize,
logout,
state,
token: () => token,
userinfo,
}}
>
{children}
</DiscordContext.Provider>
);
} and finally ...
export const HomePage: Component = () => {
const discord = useContext(DiscordContext);
createEffect(() => {
console.log(discord); // test
});
return (
<>
<h1>?????</h1>
</>
);
}; If I try to run this code the console will log: ...
import { DiscordProvider } from "./lib/discord/provider";
import { HomePage } from "./pages/Home";
const App: Component = () => {
return (
<DiscordProvider>
{() => {
createEffect(() => {
console.log(useContext(DiscordContext));
});
return <h1>Test</h1>;
}}
<HomePage />
</DiscordProvider>
);
};
export default App; The new code in this example actually does print out the correct values, whereas the still present |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem is probably here: export const DiscordProvider: Component = ({ children }) => { Destructuring children creates them outside the provider. Instead you should pass props. And access children under the provider. export const DiscordProvider: Component = (props) => {
...
return (
<DiscordContext.Provider
value={{
authorize,
logout,
state,
token: () => token,
userinfo,
}}
>
{props.children}
</DiscordContext.Provider>
);
} |
Beta Was this translation helpful? Give feedback.
The problem is probably here:
Destructuring children creates them outside the provider. Instead you should pass props. And access children under the provider.