How can we set up a Vue.js component before incorporating it into a template?

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>

Answer №1

If the variable strapiClient has been loaded, you can use a v-if condition on the Provider component to ensure it loads properly.

<Provider v-if="strapiClient" :client="strapiClient">
    <Query query= "{ questionDomains { name, description, question_topics {name,description, question_items {name, description}}}}"
        v-slot="{ data, fetching }">
        <div>
            <pre>{{ data }}</pre>
        </div>
        <span>{{jwtStrapi}} </span>
    </Query>
</Provider>
<div v-else>Fetching Data...</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with error management while using react-redux during the SignUp process

https://i.sstatic.net/OD2fl.pngWithin my component code, I handle user sign up and error checking. Initially, the error value is null. let error = useSelector((state) => state.authReducer.error); const checkErrorLoading = () => { ...

`How can I incorporate personalized animations on Google Map V3 Markers as they are individually dropped on the map?`

This is a basic example of dropping markers one by one on Google Maps V3. I have implemented the drop animation when adding markers to the map. However, I am interested in customizing the drop with a fade animation. Is it possible using JavaScript or any ...

Creating Conditional Connections in jsPlumb

Attempting to establish connections between nodes based on specific rules, such as: The "API request" endpoint is restricted from connecting to any node except "Initiate Call". The "Failed" endpoint cannot be linked to "Play Audio", and so forth. Below ...

Switch the header from left to right movement for mobile devices

I am dealing with two headers in my layout <section> <header class="col-lg-9"> <!-- some content --> </header> <header class="col-lg-3"> <!-- some content --> </header> </section ...

How can I embed certain returned values into JavaScript for display on a webpage using PHP's PDO?

I recently started learning about MVC and I'm working on retrieving an array of image paths from a MySQL database to create a grid using JavaScript. The controller needs a model that can fetch the paths from the database. Before, I had an ajax call ...

Error message: The Modelviewer is unable to load the local file, displaying the message "Unauthorized to access local resource."

For my WebAR project, I am utilizing Google's ModelViewer. In my vue.js project, I have a component that loads the model using the <model-viewer> attribute. My goal is to set the src attribute of the model-viewer to the absolute path of the .gl ...

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

Send the user to a customized dashboard depending on their user role permissions using Vue.js

Currently, I am developing a system that involves handling multiple role-permissions for users. To provide some context, there are 3 distinct users in this scenario: User1 (customer), User2 (employee), and User3 (admin). For each of these user types, I ha ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

React components receive props as an empty array when they are being passed to the component

I am passing a state to a component as a prop in the following way: componentDidMount() { axios.get("path/to/data") .then(result => { this.setState({ receivedData: result.data, }); ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

Issue with Google Adsense - adsbygoogle.push() error: Pages can only support one AdSense head tag. The additional tag will be disregarded

After adding my script tag to the navbar component, I encountered an error on my site during the next js build: Google Adsense error -adsbygoogle.push() error: Only one AdSense head tag supported per page. The second tag is ignored <Head> ...

I'm facing an issue with running npm start on my react project ever since I installed babel-cli

YTGJAI@DESKTOP-DOAIF41 MINGW64 ~/Desktop/LYNDA MERN/Exercise Files/Ch02/02_01/start/dist $ npm start [email protected] start c:\Users\mctumbaga\Desktop\LYNDA MERN\Exercise Files\Ch02\02_01\start httpster -d ...

Should you consider using the Singleton pattern in Node.js applications?

After stumbling upon this specific piece discussing the creation of a singleton in Node.js, it got me thinking. The require functionality according to the official documentation states that: Modules are cached after the first time they are loaded. Multi ...

What is the best way to implement Angular 2 slash routes in conjunction with Node Express?

I have defined some routes in my App component: @routeConfig([ { path:'login', name: 'Login', component: Login }} Additionally, I have a basic node express loader set up: var express = require('express'); var ...

Why is it that using e.preventDefault() does not prevent the link from being followed?

What is the solution to prevent a link from being followed with this specific event handler? http://jsfiddle.net/chovy/rsqH7/1/ <table> <tbody> <tr class="msg"> <header><a href="http://cn ...

Tips on how to navigate to the end of a div that has been created through ng-repeat in Angular JS with the

Here is the template code I am working with: <div class="chatbox" id="mailBody" > <div class="panel-body" ng-repeat="mail in mails"> <div class="m-b-none" ng-if="mail.inboxMessageType == 1"> <a href class="pull-left ...

Can you locate the hiding spot of the express-session cookie?

After setting a very short cookie max-age (10 secs) in my express-session, I confirmed that it is working as expected: app.use(session({ secret: 'xxx', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: 10000 } })); ...

Is Material-UI suitable for a large-scale enterprise application?

We are in the process of transforming a massive and outdated MVC Java EE application into React. This particular application consists of a browser-based user interface with an extensive range of views that include intricate forms, listings, and links. It i ...

Despite being initialized previously in JavaScript, the attribute of the object is still showing as undefined

After using an attribute from an Object multiple times, it suddenly appears as undefined when I call it in another function. Even though I have checked its values with console.log and they seem to be assigned correctly. Can anyone help me figure out what I ...