saasquatch / bunshi

Molecule pattern for jotai, valtio, zustand, nanostores, xstate, react and vue
https://www.bunshi.org/
MIT License
229 stars 17 forks source link

"Cannot call `use` outside of a molecule function" when exporting molecule from a package #76

Open dmigra0 opened 1 month ago

dmigra0 commented 1 month ago

When exporting molecule with custom scope from an npm package (i.e @my_packages/bunshi_test). In an app that uses the npm package I get the error: Cannot call use outside of a molecule function

the package code (@my_packages/bunshi_test):

import { molecule, createScope, use } from 'bunshi';
export const TestScope = createScope('none');

export const TestMolecule = molecule(
  () => {
    use(TestScope);
    return 'test';
  }
);

test app:

import { useMolecule, ScopeProvider } from 'bunshi/react';
import { TestScope, TestMolecule } from '@my_packages/bunshi_test';

const Test = () => {
  const value = useMolecule(TestMolecule);
  console.log('value:', value);
  return null
}

const App = () => {
  return (
    <ScopeProvider scope={TestScope} value="graph1" >
      <Test />
    </ScopeProvider>
  );
};
loganvolkers commented 1 week ago

You'll need to provide more details. This could be a side effect of the build system producing a bundled output, so you have two versions of bunshi in your final application.

dmigra0 commented 2 days ago

Hi, thanks for your answer. I am using nx and vite bundler with set up peerDependecies there's quite a lot of moving parts.

cmd: npm ls bunshi

returns the following: app@0.1.0 ├┬ lib1@0.1.11 │└─ bunshi@2.1.5 deduped ├┬ lib2@0.0.4 │└── bunshi@2.1.5 deduped └─ bunshi@2.1.5