Replies: 2 comments 2 replies
-
It's an imperative action, so it's basically impossible to do it in a declarative way. It's tricky, but one idea would be something like this: const inputAtom = atom(false);
const internalAtom = atom((get) => {
const input = get(inputAtom);
let value = true;
let cancel = () => {};
if (input === false) {
value = new Promise((resolve) => {
cancel = () => resolve(false);
setTimeout(() => resolve(false), 500);
});
}
return { value, cancel }
});
const outputAtom = atom(
(get) => get(internalAtom).value,
(get) => get(internalAtom).cancel()
); |
Beta Was this translation helpful? Give feedback.
-
Thanks for the starter code! What does the last line I couldn't get it working in my app and I suspect it's because of the Promise/suspense. Can the changing input trigger a delayed update without using a Promise? I don't see a way to call function useDelayedUpdater(inputAtom, outputAtom) {
const input = useAtomValue(inputAtom);
const [output, setOutput] = useAtom(outputAtom);
let timeoutId;
useEffect(()=>{
if(input){
setOutput(true);
timeoutId && clearTimeout(timeoutId);
timeoutId = undefined;
} else {
timeoutId = setTimeout(() => {
setOutput(false), 500);
timeoutId = undefined;
}
}
}, [input]);
return [output, setInput];
} Something like this seems to work. Is there a downside of wiring together atoms like this? Thanks again for the help! |
Beta Was this translation helpful? Give feedback.
-
I'm trying to create a function that returns a derived atom that has the following behavior
I'm thinking the syntax could be:
It seems like it can be done very simply but I still need to wrap my head around some things, any tips would be appreciated. Thanks
Also something like this could be useful in the utils, especially if it can be generalized.
Generalized delayed updater
where delayedSet takes in the inputAtom and a function that determines the delay for any new value.
Beta Was this translation helpful? Give feedback.
All reactions