Vue3: Implementing a single variable across multiple methods to handle authentication

It's really messing me up... I'm feeling so frustrated. How can I utilize the 'validToken' variable in order to add it to the authorization line for headers? It seems to catch an error message in the fetchHeaders function...

I am baffled as to why the authentication with 'axios' isn't working for the authorized request (it keeps returning 'headers fetched with error!'), but it works fine if I hardcode the validToken value.. The validToken is returned correctly within the template though...

Please, I need some assistance! Thank you in advance!


    #App.vue
    
    <script>
    import axios from 'axios';
    const FormData = require('form-data');
    const API_URL = "https://my_api_path.com/";
    let data = new FormData();
    data.append('username', 'my_username');
    data.append('password', 'my_password');
    let config = {
        method: 'post',
        url: `${API_URL}/login`,
        data: data
    }
    let validToken = ""
    
    export default {
        data() {
            return {
                validToken: "",
                headers: []
            }
        },
        methods: {
            async userLogin() {
                try {
                    await axios(config)
                        .then((resp) => {
                        this.validToken = resp.data.access_token;
                    });
                    Token = this.validToken;
                } catch(err) {
                    console.log(err)
                }
            },
            async fetchHeaders() {
                try {
                    let config = {
                        headers: {
                            Authorization: `Bearer ${validToken}`
                        }
                    }
                    const resp = await axios.get(`${API_URL}/headers/`,
                        config
                    )
                    this.headers = resp.data;
                } catch (err) {
                    console.error("headers fetched with error!");
                }
            }
        },
        mounted() {
            this.userLogin(),
            this.fetchHeaders()
        }
    }
    
    </script>

Answer №1

Implemented the suggestion from @EstusFlask and made necessary adjustments. The 'userLogin' function has been relocated to the mounted lifecycle method:

    async mounted() {
        await axios(config)
            .then((resp) => {
             validToken = resp.data.access_token
        });
    }

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

Reasons why `return()` and `onsubmit()` may fail when implementing a login form that redirects to a welcome page in HTML

Encountered an issue while developing a login form from HTML, CSS, and JS where the return statement was not functioning properly. Please provide code for implementing HTML embedded JavaScript. <!DOCTYPE html> <html> <head> <title& ...

Why am I receiving an error when trying to obtain context from this particular item?

I need help creating a line chart using Chart.js in Vue.js. The chart should be based on price and date data. Below is the HTML code I currently have: <div class="content"> <section class="content"> < ...

Updating a secondary state array is possible by modifying a JavaScript array with setState()

In my React application, there is a grid where names can be selected. When a name is chosen, the app retrieves corresponding data from a database and displays rows of information related to that particular name. Each row is represented as an object stored ...

Issue with App SDK: Input stream could not be parsed while executing the query

While utilizing the App SDK to retrieve all open defects within a specific project, I have encountered an unexpected issue. Despite using findAll, which should technically return all results, I am only receiving 200. The OperationResult contains the follow ...

Can JavaScript be utilized to randomly generate a predetermined link color and hover color each time the page is refreshed?

I have never ventured into the world of javascript before, but I am curious to find out if it is feasible to achieve what I have in mind before investing time in learning the language. After spending a few days browsing forums and experimenting with code ...

The variable remains unchanged even after the Vuex mutation has been executed

Currently, I am in the process of creating a settings page that involves fetching data from an API and utilizing Vuex for managing mutations. While the Vuex operations are completing successfully, it appears that the value of my dailyCount variable is not ...

Implement varying styles in React components

In my React project, I am attempting to create a unique progress bar with custom styling. Specifically, I have a dynamically calculated percentage that I want to assign as the width of a div element. Initially, I tried achieving this using Tailwind CSS: &l ...

Is it possible for JavaScript to capture scroll events while allowing clicks to pass through?

Currently, I have a setup where the user needs to interact with the layer behind the transparent scroll capture: http://jsbin.com/huxasup/4/edit?html,css,js,console,output scrollerCapture = document.querySelector('.scroller-capture'); scrollerC ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

Include the model.obj file into the three.MESH framework

I am a beginner in three.js and I am developing an augmented reality application on the web to showcase plates of food. Currently, I have successfully displayed a cube. However, when I attempted to display a model.obj instead of using geometry and material ...

Creating a Vue Directive in the form of an ES6 class: A step-by-step

Is it possible to make a Vue directive as an ES6 Class? I have been attempting to do so, but it doesn't seem to be working correctly. Here is my code snippet: import { DirectiveOptions } from 'vue'; interface WfmCarriageDirectiveModel { ...

Troubleshooting issue with ng-click functionality in AngularJS within an <li> element

When creating a pagination list image with AngularJS, I encountered an issue where the ng-click directive was not working when used in either an <li> or <a> tag. However, it worked perfectly fine within a <button> tag. <div ng-control ...

Implementing Click-Activated Scroll-to-Div Feature in React

I need to implement a scroll-to-div feature in my React App. However, the current structure of my app is preventing me from passing refs as props correctly, making it challenging to utilize ref.current.scrollIntoView(). The layout of my code looks like th ...

A JavaScript syntax problem arises when attempting to fetch data (an object) from a Laravel controller

Encountering a JavaScript syntax error in my .blade.php file when trying to access $data->modal This is my controller function: public function buku_all($page, $modal) {$data = (object) [ 'sidebar' => "pelayanan", ...

Minimal Space Separating Footer Division and Body Element

While there are numerous discussions online about fixing footer alignment issues, I've encountered a unique problem that needs addressing. The issue at hand is a 29px gap between the bottom of the footer and the <body> tag on my webpage, which ...

Refreshing and paginating data tables

I'm currently working on a basic CRUD data table and I have added a refresh function using AJAX to dynamically append HTML without reloading the page. Everything was working fine until I introduced pagination from Laravel. The issue now is that only t ...

React error due to setting div scroll height on component mount

In my code, there is a special div/container that contains multiple <p/> tags. The container has a reference called divRef, which is initially set to null using the useRef function. <div ref={divRef} style={styles.messageListContainer}> ...

Is there a way to determine the quantity of elements contained within a table by utilizing a script in Azure?

I am in need of creating an online leaderboard for a video game utilizing a Mobile Service on Azure. The goal is to have a table that only holds the top 100 scores, so as new scores are added, they should be admitted until reaching this limit. In order to ...

Hook for parsing Angular.js templates

I'm curious if Angular has a template parsing hook that can be used globally or within specific controllers. My goal is to create a language and device-specific theme loader that can dynamically retrieve resource links (such as img tags and inline st ...

Vuetify's Colored App bar unexpectedly displays as pure white

I'm having trouble with loading a Vuetify app bar using the following code: <template> <v-toolbar dark color="primary"> <v-toolbar-side-icon></v-toolbar-side-icon> <v-toolbar-title class="white--text">Title< ...