title: Understanding stores, context, sessions, and component hierarchy in Svelte/Sveltekit
body: <p>I'm familiar with Svelte but completely new to Sveltekit. I'm trying to build a Sveltekit app from scratch using AWS Cognito as the authorization tool without using AWS Amplify, using the <code>amazon-cognito-identity-js</code> sdk. I've got all the functionality working as far as login, registration, and verification, but I can't seem to get a handle on how to store the session data for the structure I've built.</p>
  <p>I've been trying to translate the strategies from this tutorial, based in React, to Sveltekit -- (AWS Cognito + React JS Tutorial - Sessions and Logging out (2020) [Ep. 3]) <a href="https://www.youtube.com/watch?v=R-3uXlTudSQ" rel="nofollow noreferrer">https://www.youtube.com/watch?v=R-3uXlTudSQ</a>
  and this REPL to understand using context in Svelte ([AD] Combining the Context API with Stores) <a href="https://svelte.dev/repl/7df82f6174b8408285a1ea0735cf2ff0" rel="nofollow noreferrer">https://svelte.dev/repl/7df82f6174b8408285a1ea0735cf2ff0</a></p>
  <p>To elaborate, I've got my structure like so (only important parts shown):</p>
  <pre><code>src
  |
  |-- components
      |-- ...
      |-- status.svelte
  |-- routes
      |
      |-- dashboard
      |-- onboarding
          |-- __layout.reset.svelte
          |-- login.svelte
          |-- signup.svelte
          |-- verify.svelte
          |-- ...
      |-- settings
      |-- __layout.svelte
      |-- index.svelte
  |-- styles
  |-- utils
      |-- cognitoTools.ts
      |-- stores.ts
  </code></pre>
  <p>I wanted to have a separate path for my onboarding pages, hence the sub-folder. My cognito-based functions reside within <code>cognitoTools.ts</code>. An example of a few functions look like:</p>
  <pre class="lang-js prettyprint-override"><code>export const Pool = new CognitoUserPool(poolData);
  
  export const User = (Username: string): any =&gt; new CognitoUser({ Username, Pool });
  
  export const Login = (username: string, password: string): any =&gt; {
      return new Promise ((resolve, reject) =&gt; User(username).authenticateUser(CognitoAuthDetails(username, password), {
          onSuccess: function(result) {
              console.log('CogTools login success result: ', result);
              resolve(result)
          },
          onFailure: function(err) {
              console.error('CogTools login err: ', err);
              reject(err)
          }
      }))
  }
  </code></pre>
  <p>I'm able to then use the methods freely anywhere:</p>
  <pre class="lang-js prettyprint-override"><code>// src/routes/onboarding/login.svelte
  import { Login, Pool } from '@utils/cognitoTools'
  import { setContext, getContext } from 'svelte'
  
  let username;
  let password;
  let session = writeable({});
  let currentSession;
  
  // Setting our userSession store to variable that will be updated
  $: userSession.set(currentSession);
  
  // Attempt to retrieve getSession func defined from wrapper component __layout.svelte
  const getSession = getContext('getSession');
  
  const handleSubmit = async (event) =&gt; {
      event.preventDefault()
          
      Login(username, password, rememberDevice)
      .then(() =&gt; {
          getSession().then((session) =&gt; {
              // userSession.set(session);
              currentSession = session;
              setContext('currentSession', userSession);
          })
      })
  }
  ...
  
  // src/routes/__layout.svelte
      ...
      const getSession = async () =&gt; {
          return await new Promise((resolve, reject) =&gt; {
              const user = Pool.getCurrentUser();
              
              if (user) {
                  user.getSession((err, session) =&gt; {
                      console.log('User get session result: ', (err ? err : session));
                      err ? reject() : resolve(session);
                  });
              } else {
                  console.log('get session no user found');
                  reject();
              }
          })
      }
  
      setContext('getSession', getSession)
  </code></pre>
  <p>Then, I've been trying to retrieve the session in <code>src/components/status.svelte</code> or <code>src/routes/__layout.svelte</code> (as I think I understand context has to be set in the top level components, and can then be used by indirect child components) to check if the context was set correctly.</p>
  <p>Something like:</p>
  <pre class="lang-js prettyprint-override"><code>
  let status = false;
  
  const user = getContext('currentSession');
  
  status = user ? true : false;
  </code></pre>
  <p>I'm running in circles and I know I'm so close to the answer. How do I use reactive context with my current file structure to accomplish this?</p>