Nuxt 3 Asynchronous Composability
P粉309989673
P粉309989673 2023-11-02 16:59:05
0
1
734

I have the following async composable in Nuxt 3 but it's not working as expected, coming from a React background I think I'm missing something.

I have the following code in my composable.

// useAsyncFoo.js
export default () => {
  const foo = ref(null);

  someAsyncFn().then(value => foo.value = value);

  return foo;
}

Then on my page I use it like this:

<script setup>
const foo = useAsyncFoo();

console.log(foo); // null
</script>

...

I want foo to get the value returned by the promise, but it is always null.

Is waiting for composables common in Nuxt 3? (await useAsyncFoo()) and export it as an async function? Did I do something wrong?

P粉309989673
P粉309989673

reply all(1)
P粉851401475

I spent an afternoon trying to transfer data from the composable to the page, but always ended up with weird or undefined data. Reading the comments here I finally figured out what I was missing and managed to do it, so thanks! If it helps, here is my file.

(FetchWrapper is a composable I made inspired by this article so I didn't have to add a token on every request, but it uses the Nuxt $fetch method.)

My composable items

export const useFoo = () => {
  const { fetchWrapper } = useFetchWrapper()
  const bar = ref([])

  const getApiData = async () => {
    try {
      bar.value = await fetchWrapper
        .get(`${useRuntimeConfig().public.API_URL}/foobar`, null)
    } catch(error) {
      //
    }
  }

  return { bar, getApiData }
}

My page

<script setup>
  const { bar, getApiData } = useFoo()
  await getApiData()
</script>

<template>
  {{ bar }}
</template>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template