11

I am using localStorage to set and get items, which is placed within my javascript code in a .vue file. However, I would like to somehow access that storage and place it within my Vuex store section which is in another file, most preferably within the mutations.

If someone knows how to do this, please could you help? Below is the code of the localStorage that I am using.

if(response.status === 200){
    console.log('TOKEN_SET', response)
    this.access_token = response.data.access_token
    localStorage.setItem(this.access_token, JSON.stringify(this.access_token));
};
mounted(){
    console.log('GOT_TOKEN')
    if(localStorage.getItem(this.access_token)) this.access_token = JSON.parse(localStorage.getItem(this.access_token))
}
YakovL
  • 7,557
  • 12
  • 62
  • 102
Aadil Hafesji
  • 383
  • 2
  • 7
  • 23

2 Answers2

17

An example of using localStorage with Vuex to store/access a token:

const store = { 
  state: {
      token: window.localStorage.getItem('token'),
  },

  mutations: {
    TOKEN: (state, value) => {
      state.token = value;
      window.localStorage.setItem('token', value);
    },
  },

  getters: {
    token: state => {
      return state.token;
    },
  },

  actions: {
    async fetchToken: ({commit}, value) => {
      const response = await fetch('/token');
      if (response.status !== 200) {
        throw new Error(`${response.status} error when fetching token!`);
      }
      const json = await response.json();
      commit('TOKEN', json.token);
    },
  },
};

No need for the init action mentioned in @ChainList's answer, unless you want conditional or delayed initialization.

Consider using sessionStorage in some cases.

To access the token use the getter:

<template>
  <section class="profile">
    <img class="picture" src="profile.png"/>
    <span class="token">{{ token }}</span>
    <button class="fetch-token" @click="fetchToken">Fetch token</button>
  </section>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
  computed: {
    ...mapGetters('token'),
  },
  methods: {
    ...mapActions('fetchToken'),
  },
};
</script>
Jonasjso
  • 361
  • 3
  • 3
13

Use mutation to set your store state AND your locale storage. When booting your application, call a store action to init your store. the code should look like the following in your mutation.

{
  mutations: {
    SET_TOKEN (state, value) {
      state.token = JSON.parse(value)
      localStorage.setItem('token', JSON.stringify(token);
    } 
  },

  getters: {
    token (state) {
      return state.token
    }
  }

  actions: {
    init(store) {
       store.actions.setToken(store, JSON.parse(localStorage.getItem('token') || ''))
    },

    setToken(store, value) {
      store.commit('SET_TOKEN', value)
    }
  }
}
ChainList
  • 1,198
  • 7
  • 28
  • 1
    Sorry, but I think I didn't explain myself properly. Basically, with the localStorage set and get items code, I would like to somehow access that and place it within my VUEX store section so that when the user logs in there email is shown in the navigation. If you know how to do this, it would be very beneficial. Sorry again and Many Thanks in advance! – Aadil Hafesji May 31 '18 at 13:17