withCompare
: A composable version of atomWithCompare
#2607
Replies: 4 comments
-
Looks interesting. Please consider opening a PR. I think it could be a good fit in recipes or in jotai/utils. @dai-shi |
Beta Was this translation helpful? Give feedback.
-
I'd suggest something like this: const identity = (x) => x;
const withCompare = (anAtom, isEqual) => {
const selected = selectAtom(anAtom, identity, isEqual);
return atom((get) => get(selected), (get, set, ...args) => set(anAtom, ...args);
}; So, your second version looks almost good. btw, we don't generally recommend It might be good for a recipe, but not for utils in which we only add some primitive ones. |
Beta Was this translation helpful? Give feedback.
-
I think the general idea to avoid, if possible, is to use JSON.parse in write, instead of read. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the review! I can put a PR up for a recipe. |
Beta Was this translation helpful? Give feedback.
-
This is a pretty simple creation, but I'm new to Jotai and this took me a while to figure out so I figured I'd share.
Context: I'm syncing an array with the URL location using
atomWithLocation
- a simplified version of my code:The issue with this is that
JSON.parse
will create a new object on everyread
, so for reference types like arrays this will trigger a rerender whenever the URL changes (sinceatomWithLocation
is subscribed to the entire URL, not just this query parameter).After fiddling around with
atomWithCompare
,useReducerAtom
, anduseAtomEffect
I eventually discoveredselectAtom
which leads to a very simple solution:And we can make it a bit more generic by accepting any type of atom 😁
Beta Was this translation helpful? Give feedback.
All reactions