Quick Start
Get started by creating a quick demo with the SpaceX GraphQL API.
Setup
- Add
nuxt-graphql-client
dependency to your project
npx nuxi@latest module add graphql-client
- Enable the module in your nuxt configuration
import { defineNuxtConfig } from 'nuxt/config'
export default defineNuxtConfig({
modules: ['nuxt-graphql-client'],
})
- Provide the URL to your GraphQL API
This can be done in either the nuxt configuration or via a .env
file.
However though, Adding the GQL_HOST
variable to your .env
would overwrite the GQL_HOST
value defined in the nuxt configuration.
import { defineNuxtConfig } from 'nuxt/config'
export default defineNuxtConfig({
modules: ['nuxt-graphql-client'],
runtimeConfig: {
public: {
GQL_HOST: 'https://api.spacex.land/graphql' // overwritten by process.env.GQL_HOST
}
}
})
- Write your GraphQL queries / mutations
.gql / .graphql
files. Writing Operations with SFC components is not supported.
nuxt-graphql-client
will automatically parse your GraphQL documents and generate the corresponding GraphQL queries / mutations../nuxt-app/queries/starlink.gql
- This will query the SpaceX API to retrieve the launches for Starlink missions.
query launches($limit: Int = 5) {
launches(limit: $limit) {
id
launch_year
mission_name
}
}
Given the query above, A Gql Function named GqlLaunches()
will be generated and accessible within the app. The Operation name (launches) in this example.
- Code Generation
Run yarn dev
for the module to generate the necessary types and functions for all GraphQL queries / mutations.
Your data will be fully-typed based on it's pertinent GraphQL Document.
- You're ready to go! ⚡️
Below is an example using the launches
query written earlier in step 4.
<template>
<div>
<h2>Starlink Launches</h2>
<p v-for="(entry, i) of data?.launches" :key="entry.id">
{{ i + 1 }}. Mission Name: {{ entry.mission_name }} ({{
entry.launch_year
}})
</p>
</div>
</template>
<script lang="ts" setup>
const { data } = await useAsyncGql({
operation: 'launches',
variables: { limit: 5 }
});
// Or: based on your preference
// const { data } = await useAsyncGql('launches', { limit: 5 });
</script>