Search code examples
javascriptvue.jsvuex

Vuex: How to change store state from a service script file state is undefined


I'm trying to change a loggedIn state in $store to true, during signup. However I get

TypeError: Cannot read property 'state' of undefined

error on line

updateLoggedIn(value)  {
        this.$store.state.loggedIn = value;
    },

in AuthenticationService.js.

./store/index.js:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    modules: {
    },
    state:  {
        token: '',
        user: null,
        loggedIn: false
    },
...

SignupPage.vue:

...
  methods:  {
    async register(formData) {
      const username = formData.get("Username");
      const email = formData.get("Email");
      const password = formData.get("Password");

      console.log(username);
      console.log(email);
      console.log(password);

      console.log("register()")
      const response = AuthenticationService.register({
        email: email,
        username: username,
        password: password
      }).then((response) => {
        console.log(response)
        console.log(this.$store)
        this.$router.push({
          name: 'ha'
        })
      },
      error =>  {
        console.log("ERROR! signup");
        console.log(error);
      });
    }
  }
...

AuthenticationService.vue:

import api from './api'

const  registeredUsers = []

export default  {
    updateLoggedIn(value)  {
        this.$store.state.loggedIn = value;
    },
    register ( credentials)  {
        registeredUsers.push(credentials);
        registeredUsers.push("nooo")
        console.log(registeredUsers)
        return api().post('register', credentials).then(
            response =>  {
               /* commit("updateLoggedInt", true);*/
                this.updateLoggedIn(true);
               /* this.$store.state.status.registerSuccess = false;*/
                console.log(this.$store);
                return Promise.resolve(response);
            },
            error =>  {
                this.$store.state.status.loggedIn = false;
                return Promise.reject(error);
            }
        )
    },
...

api.js:

import axios from 'axios'
import store from '../../src/store'

export default()  =>  {
    return axios.create({
        baseURL: 'http://localhost:8081',
        headers: {
            Authorization: `Bearer ${store.state.token}`
        }
    })
};

EDIT:

Still get the problem:

enter image description here

on line 8

import api from './api'

const  registeredUsers = []
let ref = this

export default  {
    updateLoggedIn(value)  {
        ref.$store.state.loggedIn = value;
    },
...

Solution

  • I managed to solve it.

    I added this import to AuthenticationService.js:

    import store from '../../src/store/index'
    

    and used the store object like this:

        updateLoggedIn(value)  {
            store.state.loggedIn = value;
        },