#Nanostores + Astro layout -> load initial data

5 messages · Page 1 of 1 (latest)

normal apex
#

Hey everyone, I'm just starting with Astro.
I'm wondering what's the best way to load initial data that can be shared across components like an user object.

Currently, I'm using nanostores and trying to load the initial state in the Layout.astro but the value is flickering and always falls back to the initial state of the atom() (state.set() isn't persisted on hydration it seems).

I also tried it with the @nanostores/persistent plugin but it has the same outcome.

I basically just want to load the user from a cookie (from Layout.astro) and then pass the loaded object as nanostore atom to other components.

granite bolt
#

Astro is a server side html components generation framework that also includes client side frameworks on top.
What are you using SSG, SSR ? any client side framework ? Any particular serverless deployment ?
For people not familiar with Astro, I have a set of example for small usage patterns e.g. states, cookies,... here https://github.com/MicroWebStacks/astro-examples
In short, Astro is an MPA, you cannot map an SPA concept that relies on the user never reloading the page again, more about state sharing here https://stackoverflow.com/questions/74784560/how-to-share-state-among-components-in-astro/74840400#74840400

remote niche
#

I'v just read it is now possible, if you integrate something like tanstack router I thought you could have an SPA, at the cost of losing the Astro router thus the MDX collection stuff etc.

normal apex
delicate sorrel
#

Hey @normal apex , you can hydrate state in the page component

---

const userToken = Astro.cookies.get('userToken').value;
const user = userToken ? await userStore.loginWithToken(userToken) : null;

---

<script>
  // hydrate store before client side components starts
  import userStore from '@features/auth/store/userStore';

  const user = JSON.parse(document.querySelector('[data-user]').dataset.user);

  if (user.data) {
    userStore.user.setKey('data', user.data);
    userStore.user.setKey('token', user.token);
  }

  bookingForm.set(bookingFormState);
</script>

<Layout
 ...
>
  <input type="hidden" data-user={JSON.stringify({ data: user, token: userToken })}
  />
</Layout>