-
Thank you for developing this wonderful library and providing such extensive support. IssueWhen using Jotai with Next.js, I often find myself wanting to change the behavior of Atom writers based on whether they're being called within Here's an example of an Atom with a side effect that updates another Atom to maintain the state of being changed when the original Atom is modified by the user (not by const isChangedAtom = atom(false);
const baseAtom = atom<string>('hello');
const derivedAtomWithEffect = atom<string, [update: string], void>(
(get) => get(baseAtom),
(_get, set, update) => {
set(baseAtom, update);
set(isChangedAtom, true); // this is the side effect
},
); Hydration works correctly in this case: useHydrateAtoms([
[derivedAtomWithEffect, 'Initial Content from Server'],
[isChangedAtom, false],
]); However, hydration doesn't work as expected in these cases: useHydrateAtoms([
[derivedAtomWithEffect, 'Initial Content from Server'],
]);
// or
useHydrateAtoms([
[isChangedAtom, false],
[derivedAtomWithEffect, 'Initial Content from Server'],
]); These results reflect the current implementation of
As we can see, when an Atom has side effects on write, the only way to ignore these side effects during hydration is to rely on the order of the array in This issue can also occur in other scenarios, such as:
Note: A quick solution could be to set the // define
export function atomWithSideEffects<Value, Args extends unknown[], Result>(
initialValue: Value,
writeWithDependencies: WriteWithDependencies<Value, Args, Result>,
) {
const self = atom<Value>(initialValue);
return atom<Value, Args, Result>(
(get) => get(self),
(get, set, ...args) => writeWithDependencies(get, set, self, ...args),
);
}
// use
const atomWithEffect = atomWithSideEffects<string, [update: string], void>(
'',
(_get, set, self, update) => {
set(self, update);
set(isChangedAtom, true); // this is the side effect
},
); IdeasSince hydration is a special event different from others, it would be helpful if the Writer could detect it. This would allow us to change the Writer's behavior during hydration, solving the above problem. Here are a couple of ideas: Idea 1: Add
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Thanks for opening up a discussion. I don't feel like adding anything in the core for this as there's no notion about hydrating. (btw, AFAIR, useHydrateAtoms only accepted base atoms in v1.) How about this? useHydrateAtoms([
[derivedAtomWithEffect, 'Initial Content from Server'],
[doneHydrationAtom, true],
]); |
Beta Was this translation helpful? Give feedback.
New
jotai-ssr
lib was released and it support this feature.https://www.npmjs.com/package/jotai-ssr