Nanostores is not working in Astro component

1.5k Views Asked by At

Problem: So I was able to successfully add nanostores into a React test component that I created but what I want to do is be able to use nanostores in an Astro component (*.astro). I'm trying to make just a simple web app solely in Astro with no other integrations (React, Vue, Svelte, etc).

--Dependencies--
astro: 2.0.18
nanostores: 0.7.4
preact: 10.13.1
@nanostores/preact: 0.3.1
@astrojs/preact: 2.1.0

Attempt: I created a simple nanostore here:

//userStore.js
import { atom } from 'nanostores';
export const isUserLoggedIn = atom(true);

and then imported into my Header.astro component:

//Header.astro
---
import { useStore } from '@nanostores/preact';
import { isUserLoggedIn } from '../stores/userStore';
let $isUserLoggedIn = useStore(isUserLoggedIn);
---

<nav>
  <div class='links'>
    <a href='/'>Home</a>
    <a href='/about'>About</a>
    <a href='/blog'>Blog</a>
  </div>
  <div class='links'>
    {
      $isUserLoggedIn ? (
        <a href='/logout'>Logout</a>
      ) : (
        <>
          <a href='/login'>Login</a>
          <a href='/register'>Register</a>
        </>
      )
    }
  </div>
</nav>

The error that I receive: The error that I receive

Any help would be greatly appreciated!

1

There are 1 best solutions below

0
Bryce Russell On

This does not work because .astro files are built server side and nano stores are designed to be used client side

If you want conditionally render HTML in a .astro file using login sessions you can try using SSR with a server side auth library like auth-astro or lucia-auth