Can you use async functions in atomEffect? #2432
-
I have a React app and I'm developing with Vite and SWC locally. I'm finding that if I pass an const effect = atomEffect(async () => {
// doesn't matter what's here
});
// later mounted in a component like so:
useAtom(effect) And then I save any file in my project, HMR in my app breaks and I get the following error in my browser console:
No error is found if I take off I would take a look into the jotai code, but I cannot figure out where |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Async function in atomEffect is not supported, and it's by design See discussion: jotaijs/jotai-effect#10 |
Beta Was this translation helpful? Give feedback.
-
But you can still write async code in an atomEffect atomEffect((get, set) => {
const count = get(countAtom) // countAtom is an atom dependency
const abortController = new AbortController()
;(async () => {
try {
await delay(1000)
abortController.signal.throwIfAborted()
get(dataAtom) // dataAtom is not an atom dependency
} catch (e) {
if (e instanceof AbortError) {
// async cleanup logic here
} else {
console.error(e)
}
}
})()
return () => {
// abort when countAtom changes
abortController.abort(new AbortError())
}
}) |
Beta Was this translation helpful? Give feedback.
Async function in atomEffect is not supported, and it's by design
See discussion: jotaijs/jotai-effect#10