Home » vue » Can't use cookies in Store.js file

Can't use cookies in Store.js file

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am trying to change the use of localStorage to cookies because i need to work with subdomains. When i use this.$cookie.set() or get() in any .vue file i can use with no problem but when i use in any .js file i get the following:

TypeError: Cannot read property ‘set’ of undefined.

I am using vue-cookie btw.

here is 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));
    },
Answers:

Vue.use(VueCookie) : extends the Vue object, adding the $cookie functionality to all components that inherit from it.

Vuex does not inherit from Vue, so will not have the $cookie functionality.

I just checked the vue-cookie docs and the functionality should be exposed on the global vue object via Vue.cookie

Try using the cookie on the Vue object, instead of $cookie on the Vuex one:

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

and

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