Search code examples
sveltesapper

cannot getcontext with svelte


I want to make my data globally accessible. From my understanding I can either use Context API or store and as my data is static I thought it was easier to use context API but I can't make it work.

This is my data component :

//MyDATA.svelte
<script>
   import { setContext } from "svelte";
   setContext("folioData",42);
</script>

This is the component that want to retrieve the data

//MyComponent.svelte    
<script>
  import { getContext } from "svelte";
  const folioData = getContext("folioData");
  console.log(folioData); //--------> undefined
</script>

I know, it's only the tutorial... The two files are in the same folder. Maybe there is an import problem ? The MyData file is not imported anywhere.

I'm sure this is a noob (which I am) question but I've been struggling for hours on this.

Any hint would be welcome. Thanks a lot !


Solution

  • For a simple constant I would just use a javascript file (or a module, I prefer that one).

    Example: Create a file, e.g. constants.js in your src folder (or any subfolder you want):

    export default {
      CSS_BASE_PREFIX: 'abc',
      ANIMATION_DURATION: 300
    }
    

    ...and then import it in your component:

    <script>
      import constants from './constants';
    
      const basePrefix = constants.CSS_BASE_PREFIX;
      console.log('Anim duration:', constants.ANIM_DURATION);
    </script>
    
    <div class="{basePrefix}-my-comp">...</div>
    

    It is up to you, what kind of structure you want to give it (export default, named export, etc.) Just a warning: because the imported object is a 'const' but its properties are not, you could actually overwrite them in the above example (why would you do that tho?): constants.ANIMATION_DURATION = 600; // don't do this.

    ...or you could just do this (constants.js):

    export const CSS_BASE_PREFIX = 'abc';
    export const ANIMATION_DURATION = 300;
    

    And then in your svelte component:

    <script>
      import * as constants from './constants';
    
      const basePrefix = constants.CSS_BASE_PREFIX;
      console.log('Anim duration:', constants.ANIM_DURATION);
    </script>
    

    You won't be able to reassign it anymore, it will fail at compile time. The choice is yours.