Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write-only atom in useAtomCallback does not follow scope rules for derived atoms #62

Open
koutaro-masaki opened this issue Oct 22, 2024 · 2 comments

Comments

@koutaro-masaki
Copy link

Reproduction example: https://codesandbox.io/p/sandbox/jotai-demo-forked-x6tmjn


const someAtom = atom(null, (_, set) => {
  set(baseAtom, (v) => v + 1);
});
useSetAtom(someAtom);

and

useAtomCallback((get, set) => set(baseAtom, (v) => v + 1));

should behave the same, logically.

However, inside a ScopeProvider where only baseAtom is scoped, the former follows the scope rules and accesses the scoped baseAtom, while the latter accesses the global baseAtom. Interestingly, only write-only atoms seem to ignore the scope rules. If the first argument of someAtom is changed to (get) => null, the scope rules are respected.

@dmaskasky
Copy link
Member

dmaskasky commented Oct 23, 2024

I found the root issue.

The current implementation of valued write atoms (aka write-only atoms) is to mutate the write function of the atom to intercept the getter and setter in order to resolve to nearest scoped atom. This was done to preserve the current value of the atom. Keep in mind that this value may not necessarily be null as custom write atoms can mutate themselves.

The issue with this implementation is that it only scopes the top-level valued write atom. useAtomCallback internally creates a valued write atom. Since only the baseAtom is scoped and not the write-only atom, incrementAtom1, the write chain loses scope. This is a bug.

To fix this, Jotai has recently implemented read and write traps. Implementing this new api should address this issue.

@koutaro-masaki
Copy link
Author

Thank you! I saw the draft: pmndrs/jotai#2741.
Until this is fixed, I plan to work around the issue by passing (get) => null to write-only atoms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants