Replies: 2 comments 1 reply
-
I think we should drop async effect support for now to avoid such confusions. So, follow const anEffect = atomEffect((get, set) => {
const count = get(countAtom)
const controller = new AbortController()
(async () => {
const res = await fetch('/foo/' + count, { signal: controller.signal })
if (controller.signal.aborted) return
const data = await res.json()
if (controller.signal.aborted) return
set(resultAtom, data)
})()
return () => {
controller.abort()
}
}) |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
UPDATE: PR #12 removes async effects.
loadable
and async iffe with AbortController are some good ways to implement async effects.Here is an example
https://codesandbox.io/s/epic-nash-pqkfvj
This is the conclusion to the following discussion.
When React hooks came out, there were many who felt that
useEffect
should support async callbacks. I was one of them.When starting jotai-effect, I thought it was pretty obvious to add support for async effects but didn't yet understand the caveats. As I understood this more, I realized it is important to teach caution when using async atomEffects.
1. dependencies are calculated on resolve of the returned promise
This is a big one. If you have an effect that gets an atom's value and it returns a promise, Jotai does not actually know of the effect's dependencies until the promise has resolved.
Above,
syncProcessedWithCount
will not respond to changes to count until after 1 second. This is also standard behavior in Jotai atom read functions.2. subsequent runs are aborted until the current run finishes
If the current run is still in progress when dependencies change, the change will be ignored.
3. dependencies are computed on returned promise resolve
Getting atoms with
get
in an atomEffect adds those dependencies to Jotai. Atom dependencies are evaluated when the returned promise resolves. Getting atoms after the returned promise has resolved does not add them as atom dependencies.Beta Was this translation helpful? Give feedback.
All reactions