Can I get some assistance with context usage?

I'm new to all of this and I've been trying to learn and understand for about a week now. I can't seem to get the value of 10 to display in the second example. Why does this work
import { render } from "solid-js/web";
import {
createContext,
useContext,
type ParentProps,
} from "solid-js";

const ParentContext = createContext();

function Parent(props: ParentProps) {
return (
<>
{`Parent: `}
<ParentContext.Provider value={0}>
{props.children}
</ParentContext.Provider>
</>
);
}

function App() {
const value = useContext(ParentContext);
return <>{value}</>;
}

render(
() => (
<Parent>
<App />
</Parent>
),
document.getElementById("app")!,
);
import { render } from "solid-js/web";
import {
createContext,
useContext,
type ParentProps,
} from "solid-js";

const ParentContext = createContext();

function Parent(props: ParentProps) {
return (
<>
{`Parent: `}
<ParentContext.Provider value={0}>
{props.children}
</ParentContext.Provider>
</>
);
}

function App() {
const value = useContext(ParentContext);
return <>{value}</>;
}

render(
() => (
<Parent>
<App />
</Parent>
),
document.getElementById("app")!,
);
But this one doesn't?
import { render } from "solid-js/web";
import { createContext, useContext, type ParentProps } from "solid-js";

const ParentContext = createContext();

function Parent(props: ParentProps) {
return (
<>
{`Parent: `}
<ParentContext.Provider value={10}>
{props.children}
</ParentContext.Provider>
</>
);
}

function App() {
const value = useContext(ParentContext);
return (
<>
<Parent>{value}</Parent>
</>
);
}

render(() => <App />, document.getElementById("app")!);
import { render } from "solid-js/web";
import { createContext, useContext, type ParentProps } from "solid-js";

const ParentContext = createContext();

function Parent(props: ParentProps) {
return (
<>
{`Parent: `}
<ParentContext.Provider value={10}>
{props.children}
</ParentContext.Provider>
</>
);
}

function App() {
const value = useContext(ParentContext);
return (
<>
<Parent>{value}</Parent>
</>
);
}

render(() => <App />, document.getElementById("app")!);
2 Replies
REEEEE
REEEEE7mo ago
You're accessing the context above Parent Context is like a tree/line. So where you access it, it will try to look up and get the context. Above the point where you're accessing context in the second example, there isn't a context defined
DecemberTwenty9
DecemberTwenty9OP7mo ago
Thanks a million. As soon as I read your reply, I knew what to do. I've refactored it in several ways to ensure I've understood the concept well enough and it all works. Thanks a million!
Want results from more Discord servers?
Add your server