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

Atoms generated from scoped named function will have the same values

Open hikariNTU opened this issue 1 year ago • 2 comments

We are using jotai-swc in next.js 14 with the swc plugin enabled and encounter the following issue:

When the atom is generated from a scoped named function all atoms return from that function will share the same scoped identities.

export function yieldAtoms() {
  function wrapper<T>(theAtom: PrimitiveAtom<T>): PrimitiveAtom<T> {
    return atom(
      (get) => get(theAtom),
      (_, set, arg) => {
        set(theAtom, arg);
      },
    );
  }

  const wrappedAtom = wrapper(atom(''));
  const affectedAtom = atom('');
  const someObject = { foo: 'bar' };

  return {
    wrappedAtom,
    affectedAtom,
    someObject,
  };
}
const a = yieldAtoms();
const b = yieldAtoms();

console.log({
  atomsDuplicated: a === b, // false
  wrappedDuplicated: a.wrappedAtom === b.wrappedAtom, // true
  affectedDuplicated: a.affectedAtom === b.affectedAtom, // also true
  someObjectDuplicated: a.someObject === b.someObject, // false
});

If we modify the named function part to const arrow function then the issue will be resolved:

  const wrapper = <T>(theAtom: PrimitiveAtom<T>): PrimitiveAtom<T> => {
    return atom(
      (get) => get(theAtom),
      (_, set, arg) => {
        set(theAtom, arg);
      },
    );
  };

Reproduction

https://github.com/hikariNTU/jotai-swc-test

Note

I've checked that if not enabling the plugin everything is fine, but I am not sure if the above sample code is the minimal reproduce example though since the behavior is too bizarre to get the root cause.

In the end of the day, I would probably like to see some "Caveats" section in jotai-swc documentation if these kind of bugs are as expected behaviors since they are hard to track down.

hikariNTU avatar Feb 06 '24 05:02 hikariNTU

Hi!

Thanks for reporting. 🙏🏼

Can you provide a reproduction with latest versions of the packages?

Thisen avatar Jun 13 '24 19:06 Thisen

Hi!

Thanks for reporting. 🙏🏼

Can you provide a reproduction with latest versions of the packages?

@Thisen Here https://github.com/hikariNTU/jotai-swc-test

If there's something unclear I can provide more information

hikariNTU avatar Jun 14 '24 01:06 hikariNTU

@hikariNTU with the new version of react-refresh plugin, could you check if this is still an issue? 🙏🏼

Thisen avatar Sep 03 '24 11:09 Thisen

@hikariNTU with the new version of react-refresh plugin, could you check if this is still an issue? 🙏🏼

Fixed! 0.2.0 does fix all the issues in the repository. Big thank to @martinhath 🙏🏼

hikariNTU avatar Sep 04 '24 02:09 hikariNTU