why context is undefined in svelte

Viewed 1714

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.

2 Answers

Probably it's not gonna cover this question, but keep in mind, that getContext is gonna work only for children of "setContenxt component". For cross-component sharing we should use stores.

I am writing this answer, because if I found it here, it would save me a few hours search and writing a message to the svelte community chat.

This is because contexts in Svelte are not reactive by default, when you assign tempSuggests to the context it is in fact undefined

In order to get reactivity in your context you should create tempSuggests as a store:

import { setContext } from 'svelte';
import { writable } from "svelte/store";

let tempSuggest = writable({});

const suggestModel = {
   category_id: 1,
   title: "",
   images: [{}],
   catalogues: [{}],
   dependent_attributes: [{}],
   independent_attributes: [{}],
};

$: tempSuggest.update(value => Object.assign(value, suggestModel));
setContext('clientProductSuggest', tempSuggest);

Also consider the following:

  • setContext does not have to be called inside onMount
  • the first argument of setContext should be a string (I added '')
  • suggestModel is now a store and should be treated as such in the children
Related