How to Fetch GraphQL API with Nuxt's Composition API
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>