composition-api icon indicating copy to clipboard operation
composition-api copied to clipboard

fix: allow returning of falsy values from useAsync

Open mango-martin opened this issue 3 years ago • 1 comments

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.

mango-martin avatar Aug 06 '22 06:08 mango-martin

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.

mango-martin avatar Aug 06 '22 07:08 mango-martin

I think this is a good change. Any reason you closed it?

danielroe avatar Aug 19 '22 06:08 danielroe

@danielroe Not really, I just thought it's not being considered. Reopened 👍

mango-martin avatar Aug 19 '22 06:08 mango-martin

Sorry! I know how frustrating it can be when a pr doesn't seem to be looked at. 🙏

danielroe avatar Aug 19 '22 06:08 danielroe

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. ❤️

mango-martin avatar Aug 19 '22 06:08 mango-martin