swc-jotai
swc-jotai copied to clipboard
Atoms generated from scoped named function will have the same values
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.
Hi!
Thanks for reporting. 🙏🏼
Can you provide a reproduction with latest versions of the packages?
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 with the new version of react-refresh plugin, could you check if this is still an issue? 🙏🏼
@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 🙏🏼