Currently, I am working on a Vue single file template where I need to fetch some data (a JWT token) and then use that token to make another request to a graphql endpoint. The Provider Component in my template requires the JWT Token to be set up with the :client property before rendering the template, like this:
<Provider :client="strapiClient">
. But, I am unsure about how to accomplish this step before rendering my components.
What would be the best approach? Should I handle the fetching and configuration outside of my App or inside using methods and hooks? Keep in mind that I am still relatively new to vue.js...
<template>
<Provider :client="strapiClient">
<Query query= "{ questionDomains { name, description, question_topics {name,description, question_items {name, description}}}}"
v-slot="{ data, fetching }">
<div v-if="fetching">Is Fetching ...</div>
<div v-else>
<pre>{{ data }}</pre>
</div>
<span>{{jwtStrapi}} </span>
</Query>
</Provider>
</template>
<script>
import { Provider, createClient, Query } from 'vue-gql'
// import axiosStrapi from '../components/Helpers/axios'
import axios from 'axios'
// import myImportedQuery from '../graphqlQueries/strapiquery.graphql';
const strapiRoot = 'http://localhost:1337/'
const strapiToken = await axios.post(strapiRoot + 'auth/local', {
identifier: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73071600073300070112031a5d1a1c">[email protected]</a>',
password: process.env.VUE_APP_STRAPI
})
let strapiClient
if (strapiToken) {
strapiClient = createClient({
url: strapiRoot + 'graphql',
context: () => {
return {
fetchOptions: {
headers: {
Authorization: `bearer ${strapiToken}`
}
}
}
}
})
} else {
strapiClient = createClient({
url: strapiRoot + 'graphql'
})
}
export default {
components: {
Provider,
Query
},
methods: {
init: async function () {
this.jwtStrapi = await this.getStrapiToken()
// console.log('jwtStrapi:', jwtStrapi)
// this.getStrapiClient(this.jwtStrapi)
},
getStrapiToken: async function getStrapiToken (url = strapiRoot + 'auth/local', data = {}) {
const resp = await axios.post(url, {
identifier: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c3d383135321c2f282e3d2c35723533">[email protected]</a>',
password: process.env.VUE_APP_STRAPI_PW
})
if (resp.data.jwt) {
return resp.data.jwt
}
return null
},
getStrapiClient: async function () {
const token = await this.getStrapiToken()
if (token) {
this.strapiClient = await createClient({
url: strapiRoot + 'graphql',
context: () => {
return {
fetchOptions: {
headers: {
Authorization: `bearer ${this.jwtStrapi}`
}
}
}
}
})
return this.strapiClient
} else {
this.strapiClient = await createClient({
url: strapiRoot + 'graphql'
})
return this.strapiClient
}
}
},
mounted: function () {
this.init()
},
data: function () {
return {
strapiClient,
jwtStrapi: null
}
}
}
</script>