'Sveltekit - How to access a "reactive context" (a store passed down via context) in the Script tag of Child Component?

I'm initialising a Class in the onMount function of a Parent Wrapper component and want to expose it to all the children. I'm currently using a writable store that I set to the Class in the onMount function.

let classA;
        
let classStore = writable(classA);
        
setContext('classContext', classStore);
    
onMount(async () => {
    const module = await import('library');
    const ClassInQuestion = module.default;
    
    classA = new ClassInQuestion()
    
    classStore.set(classA)
})

In a child component I'd try accessing the context like so:

const myContext = getContext('classContext');
console.log($myContext) //expected: class

What I get is undefined until I re-render the component.

I replicated a simplified version of the problem in this Stackblitz. As you can see the context gets called correctly with getContext, but in the <script> tag the old value is still being logged. Calling getContext in onMount doesn't work either. I want to access the Instance of the class and ideally update it from a child component.



Solution 1:[1]

In your child component, you could make myContext reactive so it triggers on every change

const myContext = getContext('testContext');
$: if(myContext) console.log($myContext);

The output is:

enter image description here

At this point we dont know if the child is mounted and perhaps you dont want to trigger anything before mount. Therefore, we can add further conditions e.g. waiting for the childs mount or checking a condition of myContext:

let mounted = false;
const myContext = getContext('testContext');

$: if(myContext && mounted && $myContext == "after mount") contextReady();

async function contextReady() {
    console.log($myContext)
}
    
onMount(() => {
    mounted = true;
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 m93a