fetch in createEffect?
When a set of conditions are satisfied on some state, I want to execute an http request to the server. I'd have something like:
Is it okay to initiate http request from
createEffect
? Is there anything to be aware of? I guess I don't need to use async/await? (i.e. I don't need to write createEffect(async () => // ...
) as the synchronous execution shouldn't be paused?)3 Replies
Even if you use
async
and await
, the effect stack won't pause; it will fire the asynchronous action and go onto the next effect to run.
You probably want to use async
/await
if andYetAnotherState()
needs the request of the request
One issue might be expressing the right dependencies. For an async
function, I'm not sure any of the signals called will get depended on. At best, you'd depend on the ones that get called before await
, but I'm not sure even those will work (you should test). You could use on
, or nest an async
function call inside a synchronous function that does all the signal calls.
Another potential issue is that, if the dependencies change many times, you might have many parallel fetch operations in parallel.
@mathieuprog@edemaine Ty for your help!
If I pass an
async
function to createEffect
, the following warning is emitted:
This tracked scope should not be async. Solid's reactivity only tracks synchronously.So I think that also answers the question where Solid doesn't want me to wait for an operation in
createEffect
.Ok, so you can write a synchronous function that depends on the signals you need and then calls an async function to do asynchronous work (if you want to use
await
- if you just want to launch promised you don't need a wrapper)