I'm working on a component and i need to use context for it. But i don't know why when i using getContext, It's undefined.
This is a part of my codes on first component (Index Component):
import { setContext } from 'svelte';
import {onMount} from "svelte";
let tempSuggest;
const suggestModel = {
category_id: 1,
title: "",
images: [{}],
catalogues: [{}],
dependent_attributes: [{}],
independent_attributes: [{}],
};
$: tempSuggest = Object.assign({}, suggestModel);
onMount(() => {
setContext(clientProductSuggest, tempSuggest);
});
In html codes of first component (loading sub components in the end of index file):
<svelte:component this={component} {...props}/>
In second component:
import { getContext } from 'svelte';
const c = getContext('clientProductSuggest');
console.log(c);
And now context is undefined.
It's not probably not going to cover this question but keep in mind that getContext
is only gonna work for children of the setContext
component.
For cross-component sharing we should use stores.
I am writing this answer because if I had found it here, it would have saved me a few hours of research and posting to the svelte community chat.