0

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!

angelcervera
  • 3,699
  • 1
  • 40
  • 68
jayweezy
  • 81
  • 8
  • I noticed that in the astro docs (https://docs.astro.build/en/core-concepts/sharing-state/), they don't recommend using nanostores in .astro files. So I guess I'll just have to use React components – jayweezy Mar 14 '23 at 19:58
  • That error comes from trying to use a hook outside of a component. Indeed, that will not work, you need components. – rschristian Mar 14 '23 at 23:39

1 Answers1

0

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

Bryce Russell
  • 647
  • 3
  • 8