pmndrs / swc-jotai

MIT License
87 stars 12 forks source link

TypeError: invalid value used as weak map key #17

Open yf-yang opened 10 months ago

yf-yang commented 10 months ago

Environment:

next.config.js:

experimental: {
    swcPlugins: [
      [
        '@swc-jotai/react-refresh', {}
      ],
   ],
}

Why it happen: The following lines in _component.js

const family = atomFamily((value) => {
  return atom(async () => Promise.resolve(value));
});

are compiled to the following lines in .next/server/app/page.js:

const family = globalThis.jotaiAtomCache.get(
  "/Users/admin/Workspace/jotai-swc-fast-refresh-bug/app/_component.js/family",
  (0, jotai_utils__WEBPACK_IMPORTED_MODULE_1__.atomFamily)((value) => {
    globalThis.jotaiAtomCache = globalThis.jotaiAtomCache || {
      cache: new Map(),
      get(name, inst) {
        if (this.cache.has(name)) {
          return this.cache.get(name);
        }
        this.cache.set(name, inst);
        return inst;
      },
    };
    const family = globalThis.jotaiAtomCache.get(
      "/Users/admin/Workspace/jotai-swc-fast-refresh-bug/app/_component.js/family",
      (0, jotai__WEBPACK_IMPORTED_MODULE_2__.atom)(async () =>
        Promise.resolve(value)
      )
    );
    family.debugLabel = "family";
  })
);
family.debugLabel = "family";

The external globalThis.jotaiAtomCache's entry shadows the internal one, so the internal get function actually returns undefined instead of an atom, and that undefined is passed to useAtomValue and caused the error. It happens when I call atom initializer in atomFamily or jotai-molecule molecule initializer, etc.

yf-yang commented 10 months ago

Reproduction: https://github.com/yf-yang/swc-jotai-react-refresh-error