Reputation: 13
I am trying to convert my recoil code to jotai. However, i'm having trouble understanding effects for jotai. How do i use recoil in jotai? I know they have jotai-effect but seems like its not working right
My origin recoil code
key: 'user',
default: null,
effects: [storageEffect, userEffect],
});
function storageEffect({setSelf, onSet, resetSelf}) => {
//code
}
function userEffect({setSelf}) => {
//code
}
What i did so far in jotai
const userEffect = atomEffect(() => {
storageEffect
userEffect
});
export const user = atom<any>(get => {
get(firebaseUserEffect);
});
what is the equivalent jotai code for recoil that has effects with setSelf, onSet and resetSelf?
Upvotes: 0
Views: 262
Reputation: 8930
The docs for jotai-effect are inadequate and do not give a full simple example of how to activate an effect when state changes.
This is the recipe I use when I need to run third party code conditional on an atom value (I don't even bother using jotai-effects):
const counterAtom = atom(
5, // <-- default value
(get, set, newVal) => {
// Start side effect code here
if (newVal < 0) alert('negative counter value!');
// End side effect code
set(counterAtom, newVal); // <-- update self
}
);
// If you need your effect to run on mount, then hook into the onMount method as follows:
counterAtom.onMount = (setSelf) => {
setSelf(5); // This is duplication of setting the default value (I've not found a cleaner way to avoid this repetition)
return () => {
// Cleanup code goes here if needed
};
};
Upvotes: 0