nanostores / react

React integration for Nano Stores, a tiny state manager with many atomic tree-shakable stores
MIT License
82 stars 15 forks source link

Use in a monorepo with hooks packages wrapping the store #28

Open tyom opened 2 months ago

tyom commented 2 months ago

I have encountered an issue in a monorepo setup. I created a package with nanostore that has some logic including subscriptions to the atoms. I created another package which wraps the store into custom React hooks that I would like to export as an API to access the store data. However, the consumer app loses the atom subscriptions when used via custom hooks. But it works when the custom hook is created in the consumer app.

Please see this minimal reproducible example repo.

The first button increments the count within React component but does nothing for the subscription outside. The second button updates the count in both React component and the subscription outside of React (browser console).

I assumed that the issue lies somewhere around the multiple version of the store being used but no matter what I tried with peer dependencies doesn't help.

ai commented 2 months ago

Hi. I will try to look during the week.

ai commented 2 months ago

Yes, seems like it is not a Nano Store issue but pnpm (in a way).

Since we have a multiple packages with the store, we will have 2 different stores. It is hard to image what we can do with that on Nano Stores side.

I suggest export createStore from store’s package and create all stores inside the app.

tyom commented 2 months ago

Thanks for looking into this, Andrey.

To avoid changing the store package, as it could be used directly for non-React app I think the hooks package could instead export an initialisation function that would accept the store as argument and enclose it for hooks.

What do you think of this approach?

tyom commented 2 months ago

I ended up exporting a binding function from the React hooks package that would then be bound with the store in the app.

import { store } from '@monorepo/my-store';
import { bindStore } from '@monorepo/my-react-hooks';

export const { useCounter } = bindStore(store);