Home > Net >  How to use fetched api result in other methods or functions in Nuxt3
How to use fetched api result in other methods or functions in Nuxt3

Time:06-27

How to work with fetched data from an API in Nuxt3?

For example, I want to set metatags from the API's results, but it throws an error of undefined. I am unable to access pageData in useHead.

<script setup>
import { ref } from "vue"
const { apiUrl } = useRuntimeConfig()
const route = useRoute()

const { data: pageData } = await useFetch(
  `${apiUrl}/misc/cmspage/61785b119b4eb50d8d625621`
)

useHead({
   title: this.pageData.seo.metatitle
})
</script>

This is the result of the API.

{
  seo: {
    metatitle: "SomeTitle",
    metadesc: "SomeDescriptions",
    metakeywords: "SomeKeywords",
  },
  pagename: "XXXXX",
  faqs: [],
  topDestinations: [],
  pageId: "61785b119b4eb50d8d625621",
  id: "61785b119b4eb50d8d625621",
}

CodePudding user response:

You should use pageData.value.seo.metatitle to print the content of your ref.

More details are available here: https://vuejs.org/guide/essentials/reactivity-fundamentals.html#reactive-variables-with-ref (switch to composition on the top right sidebar API preference)

  • Related