Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex/Vuejs: accessing localStorage within vuex store

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))
}
like image 961
Aadil Hafesji Avatar asked May 31 '18 11:05

Aadil Hafesji


People also ask

How do I get items from local storage in Vuejs?

Load data from local storageIn the cycle hook, we use the method localStorage. getItem('key') to retrieve data from local storage. The same key we used to store is the same we will use to retrieve the data. Add the code below just after the watch() method in App.

Does Vuex use localStorage?

A Typescript-ready Vuex plugin that enables you to save the state of your app to a persisted storage like Cookies or localStorage.

Is pinia better than Vuex?

Compared to Vuex, Pinia provides a simpler API with less ceremony, offers Composition-API-style APIs, and most importantly, has solid type inference support when used with TypeScript.

What is the use of Mapstate in Vuex?

Mapping in Vuex enables you to bind any of the state's properties, like getters, mutations, actions, or state, to a computed property in a component and use data directly from the state. Although we can get the job done with this. $store.state.user.data.name , we can use a map helper to simplify it to this.


1 Answers

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>
like image 104
Jonasjso Avatar answered Oct 01 '22 21:10

Jonasjso