swc-jotai icon indicating copy to clipboard operation
swc-jotai copied to clipboard

TypeError: invalid value used as weak map key

Open yf-yang opened this issue 1 year ago • 1 comments

Environment:

  • @swc-jotai/react-refresh 0.1.0
  • next 13.4.19 (with swc-core 1.3.80)

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 avatar Sep 18 '23 14:09 yf-yang

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

yf-yang avatar Sep 18 '23 14:09 yf-yang