-
I want to do some action when an atom's value is changed. For example, see following code.
I think it is handy if I can write code like this
Is there a utility that I can use for similar use case? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 6 replies
-
Related discussion: #1085 However, from your code snippet, you seem to expect to run the callback in sync. We don't have a capability to register such callbacks. Imperative code must be defined only in So, I would use this pattern: const countAtom = atom(0); // I would avoid exposing this to update it directly.
const doneAtom = atom(0);
const updateCount = atom(null, (get, set, arg) => {
set(countAtom, arg);
if (get(countAtom) >= 10) {
set(doneAtom, 1);
}
});
const add1Atom = atom(null, (get, set) => {
set(updateCount, get(countAtom) + 1);
});
const add3Atom = atom(null, (get, set) => {
set(updateCount, get(countAtom) + 3);
}); You could also define |
Beta Was this translation helpful? Give feedback.
-
Yes, it will works. But countAtom & doneAtom are unrelated, so I want to avoid above pattern. I thought an another example that resembles my current problem.
It worked, but it seems weired to me that decRange can change the currentAtom. My another solution that applied to my previous similar problem is using callback atom.
Actually, I want to modularize some atoms, so breaking dependencies is important. If there is no good solution, I also think write-only atom is the only way as you wrote. |
Beta Was this translation helpful? Give feedback.
-
I used Mithril.js prior to React. With Stream I can write like this.
I thought stream is very similiary to Jotai's atom. I just missed that pattern. (Yes. map is for computed properties(derived atoms), and it may be not a good pattern 😞 ) |
Beta Was this translation helpful? Give feedback.
-
@dai-shi I'm wondering if there are any further optimizations possible for such an implementation? I tried an implementation in something like jotai-effect and found that I couldn't read the previous variables. Also my code can't avoid multiple updates in a short period of time, what should I do to do this? Maybe debounce fn is needed? export const designStore = atom(
(get) => {
return get(appStore).design;
},
(get, set, setValue: SetStateAction<IDesignStore>) => {
set(appStore, (prev) => {
const newValue = {
...prev,
design: callSetState(prev.design, setValue),
} as IAppStore;
if (!get(historyStore).isPause) {
const previousState = prev.design;
const currentState = newValue.design;
const diffResult = diff(previousState, currentState);
set(historyStore, (prev) => {
return {
...prev,
undoStack: [...prev.undoStack, diffResult],
redoStack: [],
} as IHistoryStore;
});
}
return newValue;
});
},
); |
Beta Was this translation helpful? Give feedback.
Yes, it will works. But countAtom & doneAtom are unrelated, so I want to avoid above pattern.
I thought an another example that resembles my current problem.