composition-api
composition-api copied to clipboard
fix: allow returning of falsy values from useAsync
Related to #493
If a falsy value is returned from useAsync, the client will always run the request again.
You could completely allow falsy values by adding a hasRun ssrRef but I fear it would pollute the global space.
So, as a compromise, with this change you can avoid having the client re-run a request if you return any falsy value other than null (and void)
Edit:
I guess another solution would be to convert the default ref value to an object, something like { data: null, hasRun: false } and maintain the single ssrRef that's already generated currently. But I think the proposed change is simple enough and really has no downsides to current behavior afaik.
To give a bit more context.
This is useful for error handling, like this.
<template>
<div>
<ClientOnly>
<DataComponent v-if="data" :data="data" />
<p v-else>404</p>
</ClientOnly>
</div>
<template>
<script setup>
import { myFetch } from '~/utils'
const data = useAsync(async () => {
try {
const result = await myFetch.do()
return result
} catch {
return false
}
})
</script>
Currently this kind of code will always send requests on both server and client process. With the change it will only run once.
I think this is a good change. Any reason you closed it?
@danielroe Not really, I just thought it's not being considered. Reopened 👍
Sorry! I know how frustrating it can be when a pr doesn't seem to be looked at. 🙏
Sorry! I know how frustrating it can be when a pr doesn't seem to be looked at. 🙏
No worries. I know you're super busy with Nuxt 3 atm. ❤️