Why is it that vue-cookies are functioning properly in one view, yet not in another?

In my Login.vue file, I successfully set a token cookie using the 'vue-cookies' package. The cookie is properly set and working.

However, when I try to access the same cookie in another view, I encounter the following error in the Chrome console:

Uncaught (in promise) TypeError: Cannot read property 'get' of undefined
        at _callee$ (Dashboard.vue?98fa:19)
        at tryCatch (runtime.js?96cf:63)
        at Generator.invoke [as _invoke] (runtime.js?96cf:293)
        at Generator.eval [as next] (runtime.js?96cf:118)
        at asyncGeneratorStep (asyncToGenerator.js?1da1:3)
        at _next (asyncToGenerator.js?1da1:25)
        at eval (asyncToGenerator.js?1da1:32)
        at new Promise (<anonymous>)
        at eval (asyncToGenerator.js?1da1:21)
        at VueComponent.getWallets (Dashboard.vue?98fa:18)
    

Here is an excerpt from the Login.vue component where the cookie setting takes place:

<template>
  <div class="login">
    <!-- Login Form HTML here -->
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      email: this.email,
      password: this.password
    };
  },
  components: {},
  methods: {
    async login() {
      // Login method code here
      // Cookie is set successfully in this component
    }
  }
};
</script>

Problem arises in Dashboard.vue component where the cookie retrieval fails:

<template>
  <div>
    <h1>This is the dashboard</h1>
  </div>
</template>

<script>
export default {
  name: "Dashboard",
  data() {
    return {
      wallets: this.wallets,
      user: this.user
    };
  },
  components: {},
  methods: {
    async getWallets() {
      var token = this.$cookies.get("token");
      let config = {
          headers: { Authorization: 'Bearer ' + token }
      };
      // Error occurs while trying to retrieve the cookie here
    }
  },
  mounted: function() {
      this.getWallets();
  }
};
</script>

Lastly, here are the contents of main.js:

import Vue from "vue";
import App from "./App.vue";
// Other imports

Vue.config.productionTip = false;

new Vue({
  // App initialization
}).$mount("#app");

Vue.use(VueCookies);
Vue.$cookies.config("7d");

Answer №1

For proper functionality, ensure that plugins are installed prior to initializing the Vue instance. To accomplish this, simply move the installation of the VueCookies plugin above the creation of the new Vue instance:

Vue.use(VueCookies);
Vue.$cookies.config("7d");

new Vue({
  router,
  store,
  axios,
  render: h => h(App)
}).$mount("#app");

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

Using Jest's moduleNameMapper with Next.js without TypeScript

I've been encountering some challenges trying to implement moduleNameMapper in NextJS using JavaScript. In this particular project, TypeScript is not being utilized. Next: 12.2.5 React: 18.2.0 Jest: 29.0.1 Jest environment jsdom: 29.0.1 Below is the ...

"Encountering errors when using the vue-notification library in the

Currently, I am in the process of working on a project utilizing vuepress along with the vue-notification package. The project runs smoothly when I execute it locally using the vuepress dev command. However, upon attempting to build the project, the follo ...

Using AngularJS to Nest ng-view within ng-repeat

I have a collection of items. Each item has buttons to display its details and comments within this ng-view section. It is necessary for the user to view all available product details on one page, for example. Below is the HTML list: <div ng-controll ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Jquery each function not correctly retrieving all elements with the specified class

I created a page featuring a search box and 5 Bootstrap Cards. I set it up so that the cards would hide if the text typed in the search box does not match the content within the data-tags attribute. Everything seems to be working fine, except that it is on ...

Is there a way to prevent my token from being exposed when making an AJAX call?

When working on my HTML file, I encountered an issue with a Python Django URL integration where I need to pass a token to retrieve certain information. However, the problem is that my token is exposed when inspecting the page source in the HTML document. ...

Providing the module with the URL

How can I retrieve the URL within a module? module.exports = function(app, Reviews, Anon, User, url){ var url = url; console.log("url", url)// url is undefined how to get url function postHandler(req, res){ } app.post("/individual/"+ u ...

Guide on how to refresh the 'id' after a set period using Ajax technology

I am having an issue with reloading/refreshing a specific table in order to fetch updated database information. The problem is that when I try to refresh only the table, the entire page reloads instead. However, I have managed to identify the 'id&apos ...

Issue with data binding click event not functioning on Chrome when used within a nested for loop

Currently, the code below is functioning properly in Internet Explorer. It involves a download link that is disabled based on a condition. However, the same code does not work in Chrome. In Chrome, the Link remains enabled and does not disable as expected ...

The AngularJS change event is not being activated

I am a beginner with angular js and I have implemented a bootstrap calendar in my application. However, I am facing an issue where the change event is not being triggered when the month changes, no matter where I place it within the code. Here is the snip ...

Python Selenium not registering button click

I'm working on scraping data from the website using Python with Selenium and BeautifulSoup. This is the code I have: driver = webdriver.Chrome('my file path') driver.get('https://www.ilcollege2career.com/#/') first_click = Web ...

List of Map Pins on Google Maps

I am looking to integrate PHP and Javascript to display multiple markers (at least 50) on a Google map. After reviewing the documentation at: https://developers.google.com/maps/documentation/javascript/examples/map-latlng-literal I noticed on line 15 it m ...

Displaying Kartik's growling animation using AJAX within Yii2 framework

Utilizing kartik growl to display a message via ajax success I attempted the following: This is the javascript code: $.post({ url: "forwardpr", // your controller action dataType: 'json', data: {keylist: keys,user:userdata}, success: f ...

The Bootstrap 4 modal appears to be failing to load properly, as it is only

Trying to trigger a Bootstrap modal with a button click. Currently, there is one functioning modal on the page that works fine. However, when attempting to load another modal on a button click, only a faded screen appears. <button class="btn btn-green ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...

Is PHP loaded prior to the `html body`?

I'm facing a unique challenge where I am currently transferring variables from a PHP page to hidden HTML inputs. The values are extracted from these hidden inputs using a JavaScript function that is called in the following manner: <body onload=" ...

Stop the promise chain when the first error callback is encountered

Here is a sequence of promises I am dealing with: Transaction.findPublic({}).then(function(transactions) { combined = combined.concat(transactions); return JoinEvent.find().exec(); }, function(err) { return res.status(503).send(er ...

Handling dynamic routes with React Router 4 and the 404 path

I have been working with the latest version of React Router (4) and have implemented a dynamic route configuration as described in the tutorial. The routes are functioning correctly, except for when I tried to add a 404 path following the tutorial's i ...

how to switch back and forth between div elements in vue js

I'm currently attempting to toggle between divs, but I'm running into some difficulties. I've realized that I can't include two elements inside the transition directly, and that I need to use a transition-group for this purpose. However ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...