pmndrs / swc-jotai

MIT License
90 stars 14 forks source link

Atoms generated from scoped named function will have the same values #25

Closed hikariNTU closed 3 days ago

hikariNTU commented 7 months ago

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.

Thisen commented 2 months ago

Hi!

Thanks for reporting. πŸ™πŸΌ

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

hikariNTU commented 2 months ago

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

Thisen commented 3 days ago

@hikariNTU with the new version of react-refresh plugin, could you check if this is still an issue? πŸ™πŸΌ

hikariNTU commented 3 days ago

@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 πŸ™πŸΌ