Utilizing Local Storage in Vuex Store with Vue.js

I have been working with localStorage for storing and retrieving items in my JavaScript code housed within a .vue file. However, I am now looking to find a way to transfer this stored data into my Vuex store, specifically within the mutations section located in another file.

If anyone has any insights or suggestions on how to achieve this, your help would be greatly appreciated. Provided below is the snippet of code showcasing how I am currently utilizing localStorage.

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))
}

Answer №1

Illustrative example showcasing the utilization of localStorage in conjunction with Vuex for storing and retrieving 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 requirement for the mentioned init action as described in @ChainList's answer, unless there is a necessity for conditional or delayed initialization.

It could be beneficial to utilize sessionStorage in specific scenarios.

To retrieve the token, access it via 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>

Answer №2

Utilize mutation to update both your store state and local storage simultaneously. When starting up your application, invoke a store action to initialize your store. Here is an example of how the code should appear within 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)
    }
  }
}

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

What is the best way to include default text in my HTML input text field?

Is it possible to include uneditable default text within an HTML input field? https://i.stack.imgur.com/eklro.png Below is the current snippet of my HTML code: <input type="text" class="form-control input-sm" name="guardian_officeno" placeholder="Off ...

Retrieve information using server-side rendering

I'm faced with a situation where my page utilizes query parameters to fetch data via SSR. The challenge arises when these query parameters frequently change, triggering a re-fetch of the data using SSR despite there being no client-side data fetching ...

Unable to access a hyperlink, the URL simply disregards any parameters

When I click an a tag in React, it doesn't take me to the specified href. Instead, it removes all parameters in the URL after the "?". For example, if I'm on http://localhost:6006/iframe.html?selectedKind=Survey&selectedStory=...etc, clicking ...

Preserving scroll position during page navigation in Next.js

Currently, I am working on a website using the Next.js boilerplate. Here is the routing code that I am using: import Link from 'next/link' <Link href={{ pathname: '/some-url', query: { param: something } }}> <div> ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

Tips for modifying the properties of variables within an array using JavaScript

I have an array that holds variables used to control a specific template. divisionsListToManipulate: ['showActivitiesSection', 'hideAssignActionplanDiv', 'displayProp ...

Angular functions are executed twice upon being invoked within the html file

I decided to kick-start an Angular project, and I began by creating a simple component. However, I encountered a perplexing issue. Every time I call a function in the HTML file from the TypeScript file, it runs twice. TS: import { Component, OnInit } from ...

Error receiving parameter in express route callback function

At the moment, I have been working with a number of routes in Express. Some routes are quite lengthy and tend to look like this: router.get('/api/comments', function(req, res, next){ Comment.find({"user": req.payload._id}).exec(function(err,co ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Can you point me to the source of definition for Vue 2's ComponentDefinition and ComponentConstructor types?

I am struggling to add a dynamic Vue 2 component with correct typing in TypeScript. The documentation clearly mentions that the is attribute accepts values of type string | ComponentDefinition | ComponentConstructor, but I cannot locate these custom types ...

A guide on organizing the visible items in a vue table

I need help with two issues related to this code snippet. 1. The first problem arises when I have an array containing four items with IDs [1, 2, 4, 5, 7]. If I select to display 2 items per page and click on the sort function, it shows entries with IDs 1& ...

Identify the browser dimensions and implement CSS styling for all screen resolutions

I am currently facing an issue with a function that I have created to apply CSS changes to a menu based on browser resizing and different resolutions. The problem lies in the fact that my function does not seem to be correctly interpreted by the browser. W ...

Understanding image sizes for uploads on Tumblr can be a bit confusing, especially when comparing pages to posts. Learn how to implement lazyloading for post

I'm currently working on a highly customized Tumblr account that features a mix of pages and posts. I am looking to access content and assets, particularly images, from these pages/posts for use in other parts of the site. When I upload an image to a ...

Check to see if modifying the HTML using jQuery results in any errors

Although it may sound straightforward, let me clarify. I am utilizing ajax calls to update the content of the body and I aim to trigger an alert if the updating process fails on the client side, specifically after receiving a response from ajax in case of ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Implementing automatic activation of a tab upon page load using Angular

I am currently working with a set of Bootstrap nav pills in my navigation bar. The 'ng-init' code in my Angular script sets the 'dateState' to 'past' on page load. However, I have noticed that the 'Past Events' nav p ...

Executing commands following a JSON loop in jQuery

I'm experiencing an issue with jQuery. When my page loads, I fetch a JSON file and loop through its items. However, I am unable to attach any event listeners to the input button that is added. For instance, I want to display an alert message... It s ...

How to access a namespaced getter from a Vue template using Vuex

I've recently set up a Vuex namespaced getter mapping in my .vue file with the following code: ...mapGetters([ 'fooModule/barGetter' ]) Now, I'm trying to figure out how to access this specific getter in the template of the .vue comp ...

JQuery UI Autocomplete: Results, Ctrl + A and Delete

I am currently designing a form that allows users to add members to a project. Only members with existing profiles in the system can be added. The form includes an input field for the member's name and a select box for their position, which is initial ...

How can I check if the VPN is turned off in a React application?

import React from "react"; import { Offline, Online } from "react-detect-offline"; export default function DropDown() { return ( <> <Online>Only displayed when connected to the internet</Online> <Offline ...