How to Fetch GraphQL API with Nuxt's Composition API

Nuxt guide logo
Related module need to be install first. Nuxt 2 using Nuxt's Strapi module

In Nuxt 2

Inside script tag:

                                
                                        <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:

                                <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