Astro: Access nano store hook "useStore" from a *.astro file

1.6k Views Asked by At

I've defined a nano store in src/themeStore.ts:

import { atom } from 'nanostores';
export const theme = atom('blue');

I'm trying to access the store's value in the front-matter of an *.astro file.

src/pages/samples/[id].astro:

import { useStore } from '@nanostores/react';
import { theme } from '../../themeStore';
const $theme = useStore(theme); // error

The following error is thrown to the terminal console:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
 error   Cannot read property 'useCallback' of null
  Code:
      1645 |   var dispatcher = resolveDispatcher();
    > 1646 |   return dispatcher.useCallback(callback, deps);
           |                     ^
      1647 | }
      1648 | function useMemo(create, deps) {
      1649 |   var dispatcher = resolveDispatcher();

It makes sense...I'm trying to run a hook and I'm not within a functional component. I've seen this error before when using other React projects.

One potential solution would be to convert to jsx files, rather than astro, but that would be a refactor we could hopefully avoid.

Is there a way to access nano stores from a "*.astro" file when using React with Astro?

1

There are 1 best solutions below

0
On

You can use .get() to read the store outside of React (including in Astro components):

import { theme } from '../../themeStore';
const themeState = theme.get();

You should still use useStore in React components.