nhatimme
nhatimme

Reputation: 421

Nuxt3 - Using useFetch inside composable and return / use it inside a template

I created a template which runs a function from a composable. Inside the composable function I use useFetch to make a server side API call. I store the return value inside data as variable.

The problem is; The return/value gives me the following output: "[object Promise]"

Template: Home.vue

<script lang="ts" setup>
import { useAccount } from "@/stores/account";
import { menu } from "@/data/account"

definePageMeta({
  layout: 'checkout',
})
const account = useAccount();

const { processEmail, testTest } = await useCheckout();

</script>

<template>
  <div class="flex min-h-full flex-col justify-center py-12 sm:px-6 lg:px-8">
    Data: {{ testTest() }} 
  </div>
</template>

Composable: useTest.ts

export const useCheckout = async () => {
 
  const testTest = async () => {
    const { data: element } = await useFetch('https://www.boredapi.com/api/activity');
    return element
  }

  return {
    testTest
  }
}

Upvotes: 0

Views: 5619

Answers (1)

Felix Ekl&#246;f
Felix Ekl&#246;f

Reputation: 3740

You're awaiting the useCheckout (Which doesn't need to be async since it doesn't use await.) function but not the testTest function. This should work:

<script lang="ts" setup>
import { useAccount } from "@/stores/account";
import { menu } from "@/data/account"

definePageMeta({
  layout: 'checkout',
})
const account = useAccount();

const { processEmail, testTest } = await useCheckout();
const data = await testTest();

</script>

<template>
  <div class="flex min-h-full flex-col justify-center py-12 sm:px-6 lg:px-8">
    Data: {{ data }} 
  </div>
</template>

Upvotes: 2

Related Questions