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

React refresh overwrites array of anonymous atoms on assignment

Open nickbabcock opened this issue 1 year ago • 1 comments

import {atom} from "jotai";
const abc = [atom("message")];
console.log(abc.length):
// Outputs undefined

Instead abc is now an atom (init, read, write properties), so I believe something is causing abc to be overwritten.

Amusingly, the following works as expected

import {atom} from "jotai";
console.log([atom("message")].length):
// Outputs 1

If I remove @swc-jotai/react-refresh from the list of swc plugins, it works. What could be the problem?

It seems to be a general problem where assigning a variable with an expression that involves atoms will assume that the variable is the atom.

const abc = () => [atom('message')]
// abc is once again an atom

A workaround is to wrap the construction in a named function.

function abc() {
  return [atom('message')];
}
const foo = abc();
console.log(foo.length) // 1 !

nickbabcock avatar Mar 04 '24 13:03 nickbabcock

I've added this to my issue reproduction as well, seems like they are similar issue where atom is included in array and some assignment is not linked correctly

image

  • #25

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

hikariNTU avatar Jun 14 '24 03:06 hikariNTU