Unable to utilize cookies within the Store.js script

I am currently in the process of transitioning from localStorage to cookies because I need to work with subdomains. Strangely, when I use this.$cookie.set() or get() in any .vue file, it works perfectly fine. However, when I try to use it in any .js file, I encounter the following error:

TypeError: Cannot read property 'set' of undefined.

Just a heads up, I am using vue-cookie for this implementation.

Below is an excerpt from my store.js file:

import Vue from "vue";
import Vuex from "vuex";
import axios from "./axios-auth.js";
import globalAxios from "axios";
import router from "./router";
import VueCookie from 'vue-cookie';
Vue.use(VueCookie)
Vue.use(Vuex);

export default new Vuex.Store({
state: {
    token: null,
    userId: null,
    expireIn: null,
    segmentoSelecionado: null,
    codigoTransfSelecionado: null
},
actions: {
login({ commit }, authData) {
      axios
        .post("/auth", {
          username: authData.username,
          password: authData.password,
          returnSecureToken: true
        })
        .then(res => {
          const now = new Date().getTime();
          const expirationDate = new Date(now + 3500000).getTime();
          this.$cookie.set('userToken', res.data.token, {domain: 'subdomain.domain.com'});
          commit("authUser", {
            userToken: this.$cookie.get('userToken'),
          });
        .catch(error => console.log(error));
    },

Answer №1

When using VueCookie plugin with Vue.js,
the Vue object is extended to include the $cookie functionality for all components that inherit from it.

It's important to note that Vuex, however, does not inherit from Vue and therefore does not have access to the $cookie functionality.

Referencing the vue-cookie documentation, you can see that the functionality is exposed on the global vue object as Vue.cookie.

To implement cookies, use the code below with the Vue object instead of the Vuex object:

Vue.cookie.set('userToken', res.data.token, {domain: 'subdomain.domain.com'});

and

userToken: Vue.cookie.get('userToken')

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

Unable to assign the value 'hello' to an undefined property in TypeScript

I'm attempting to define a class in TypeScript, but I keep encountering the error shown below. Here is the execution log where the error occurs: [LOG]: "adding" [LOG]: undefined [ERR]: Cannot set property 'hello' of undefined class Cust ...

What is the best way to add or delete data when specific radio buttons are chosen?

Hey there, I'm facing an issue where the data is being appended regardless of which radio button is selected. Can someone help me with a solution on how to properly add and remove data based on the selected radio button? $( document ).ready(functio ...

Reverse the action and postpone the Ajax call for a specified time or until the next action occurs

How can I implement a setup and undo feature for my ajax calls that allows users to delay the call for a set amount of time and abort it if needed? I also want to be able to stop the delay and proceed with the most recent ajax call if another action is tri ...

Having trouble with Node.js multiparty upload functionality

I'm facing an issue with the functionality of multiparty.Form(). Specifically, I am attempting to print numbers like 2, 3, and 4. Below is the code snippet for uploading images: app.post('/gallery/add',function(req, res,next) { var input = ...

Using JavaScript to add a Vue component and display it on a page

I am working with a Vue component that is imported in a component file. My goal is to render another component using the append function. How can I achieve this? <template> <JqxGrid :width="width" :source="dataAdapter" :columns="gridValues" ...

In the Vue.js framework, ensure the boolean value is set to false whenever a key is pressed, with

Hi everyone, I'm currently working on an input form and my goal is to change the showTag value to false when any button other than the enter key is pressed. Specifically, I want the showTag boolean to be set to false after pressing the delete button o ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...

Using Javascript to restore image to its original state in OpenCart 2.3

I recently created a JavaScript function that successfully replaces the main image on a product page with a different image when clicked. While this feature is functioning perfectly, I am struggling to make the original image return once the mouse leaves t ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

Issues with rendering Google Maps on google-maps-react persists, stuck endlessly in loading phase

After following the tutorial for google-maps-react, I attempted to display a Google Map in my app using the same structure as the example. However, the map is not rendering. Link to Tutorial There are no errors showing up in my console. Here is the dire ...

Displaying a pop-up message using JavaScript: How to trigger it with jQuery

Within my application, I have successfully implemented a basic JavaScript popup by invoking it in this manner- <a href="javascript:popup('Hello World')>Click Me</a> I am curious if it is feasible to trigger the same popup using othe ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

Creating diverse content for various tabs using JavaScript

I have developed a code that uses a for loop to generate tabs based on user input. var tabs = ""; var y = 1; for (var x = 0; x < tabNum; x++) { tabs += "<li class = 'tabbers'>" + "<a href='#tab'>Tab</a>" + "& ...

Unable to save the current light/dark mode preference to local storage

Being a beginner in JavaScript, I am currently working on implementing a simple light mode button for my website which defaults to dark mode. The transition between JS/CSS dark and light modes is seamless, giving the site an appealing look when switching t ...

jQuery Mishap - Creating an Unspecified Issue

At the moment, my website displays a list of registered users in one column and their email addresses with checkboxes next to them in another column. Users can check the boxes and then click a submit button to generate a list of the selected emails separat ...

Application unable to save data to file with no indication in error logs

Recently, I've been experimenting with the Capture-Website package, which is designed to save website screenshots to a file. Initially, everything was working smoothly until I decided to restart the server. Now, although my code is running without a ...

Is there a way in JavaScript to launch a link in a new tab and overlay a div on top of the existing content of the page?

Is there any method in JavaScript to open a link in a new tab and add a div element on that page? Let's say I have a page called page1.html which has a div containing a link and two radio buttons "yes" and "no". I want to open the link in a separate t ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

How can I display a particular section of my JSON data in an AngularJS application?

Below is an example of a JSON structure: {"years":[ { "year_title":"94", "months":[...] } { "year_title":"95", "months":[...] } { "year_title":"96", "months":[...] } ]} I was able to display the data using the code sni ...

Strategies for preserving context throughout an Ajax request

In my project, I am looking to implement an Ajax call that will update a specific child element within the DOM based on the element clicked. Here is an example of the HTML structure: <div class="divClass"> <p class="pClass1">1</p> &l ...