How to properly pass instance created in onMount()
to child components?
#1992
Unanswered
MarByteBeep
asked this question in
Q&A
Replies: 1 comment
-
I think I solved it using import { Show, createSignal, onMount } from 'solid-js';
import { Foo, MyContext } from './MyContext';
export default function Parent(props: any) {
const [foo, setFoo] = createSignal<Foo>();
onMount(() => {
setFoo(new Foo());
});
return (
<Show when={foo()}>
{(value) => (
<MyContext.Provider value={value()}>
<div>Parent {value().bar}</div>
{props.children}
</MyContext.Provider>
)}
</Show>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'd like to create an instance of some class
Foo
in a parent component'sonMount()
and let all its child components be able to access and use that instance.I only have a single instance of
Foo
in my entire application and the instance ofFoo
needs to be created inonMount
, so it only becomes available after the initial render. This complicates things.This is the example I tried so far, using a
Context
, which resulted in a bunch ofVariable 'foo' is used before being assigned.
warnings, which obviously resulted in run-time errors:TypeError: Cannot read properties of undefined (reading 'bar')
.So... how to do this properly in Solid?
MyContext.ts
Parent.tsx
Child.tsx
And finally the
App.tsx
:Beta Was this translation helpful? Give feedback.
All reactions