pmndrs/swc-jotai

TypeError: invalid value used as weak map key

Open

#17 aberto em 18 de set. de 2023

Ver no GitHub
 (1 comment) (4 reactions) (0 assignees)Rust (21 forks)github user discovery
bughelp wanted

Métricas do repositório

Stars
 (104 stars)
Métricas de merge de PR
 (Métricas PR pendentes)

Description

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.

Guia do colaborador