title: Svelte access a store variable in child component script tag
body: <p>I have a Svelte &amp; Sapper app where I am using a Svelte writable store to set up a variable with an initial blank string value:</p>
  
  <pre><code>import { writable } from 'svelte/store';
  export let dbLeaveYear = writable('');
  </code></pre>
  
  <p>In my <code>Index.svelte</code> file I am importing this and then working out the value of this variable and setting it (I am doing this within the <code>onMount</code> function of ```Index.svelte if this is relevant):</p>
  
  <pre><code>&lt;script&gt;
    import {dbLeaveYear} from "../stores/store.js"
  
    function getCurrentLeaveYear() {
      const today = new Date();
      const currYear = today.getFullYear();
      const twoDigitYear = currYear.toString().slice(-2);
      const cutoffDate = `${twoDigitYear}-04-01`
      const result = compareAsc(today, new Date(cutoffDate));
      if (result === -1) {
        $dbLeaveYear = `${parseInt(twoDigitYear, 10) - 1}${twoDigitYear}`;
      } else {
        $dbLeaveYear = `${twoDigitYear}${parseInt(twoDigitYear, 10) + 1}`;
      }
    }
  
    onMount(() =&gt; {
      getCurrentLeaveYear();
    });
  &lt;/script&gt;
  </code></pre>
  
  <p>I have a child component being rendered in the <code>Index.svelte</code></p>
  
  <pre><code>&lt;Calendar /&gt;
  </code></pre>
  
  <p>Inside the Calendar child component I am importing the variable and trying to access it to perform a transform on it but I am getting errors that it is still blank - it is seemingly not picking up the assignment from <code>Index.svelte</code>:</p>
  
  <pre><code>&lt;script&gt;
    import {dbLeaveYear} from "../stores/store.js"
    const calStart = $dbLeaveYear.slice(0, 2)
  &lt;/script&gt;
  </code></pre>
  
  <p>However if I use the value in an HTML element in the same Calendar child component with <code>&lt;p&gt;{$dbLeaveYear}&lt;/p&gt;</code> it is populated with the value from the calculation in <code>Index.svelte</code>.</p>
  
  <p>How can I access the store variable inside the <code>&lt;script&gt;</code> tag of the child component?  Is this even possible?  I've tried assiging in <code>onMount</code>, I've tried assigning in a function - nothing seems to work and it always says that <code>$dbLeaveYear</code> is a blank string.</p>
  
  <p>I need the value to be dynamic as the leave year value can change.</p>