How to Fetch GraphQL API with Nuxt's Composition API

Nuxt guide logo

Replace with note

In Nuxt 2

Inside script tag:

typescript
<script lang="ts">
import { defineComponent, ref, useFetch } from '@nuxtjs/composition-api';
// this will be the GraphQL query string
const query = (): string => {
  return  `query posts {
   Posts {
    title
   }
  }`;
};

export default defineComponent({
  setup() {
    // variable to hold the content
    const content = ref();
    // using useFetch from Composition API
    useFetch(async ({ $strapi }) => {
      try {
        // Assign the data to content variable
        content.value = await $strapi.graphql({
          query: query(),
        });
      } catch (error) {
        console.error('Error: ', error);
      }
    }
  }
});

return { content };

</script>

Inside template tag:

html
<template>
  <section>
    <!-- content contain our data from useFetch -->
    {{ content }}
  </section>
</template>
Next post How to add CSS class dynamically on the HTML body in Nuxt