Issue with Vuex: currentUser state not persisting after page refresh

I'm currently working on a Vue.js SPA that utilizes Rails 6 API as the backend and Vue-cli (legacy webpack template).

After signing in a user, everything seems to be functioning correctly. I can view the user details, it updates my setCurrentUser mutation and state. However, when I navigate away from the dashboard, I lose all the user's state. The Vue dev tools panel indicates that everything resets back to false.

As I am new to Vue/Vuex, I suspect this might be an oversight on my part.

Here is my signin method for fetching the current user:

 methods: {
    signin () {
      let formData = new FormData()
      formData.append('user[email]', this.user.email)
      formData.append('user[password]', this.user.password)

      this.$http.plain.post('/signin', formData, { emulateJSON: true })
        .then(response => this.signinSuccessful(response))
        .catch(error => this.signinFailed(error))
    },
    signinSuccessful (response) {
      if (!response.data.csrf) {
        this.signinFailed(response)
        return
      }
      this.$http.plain.get('/api/v1/me')
        .then(meResponse => {
          this.$store.commit('setCurrentUser', { currentUser: meResponse.data, csrf: response.data.csrf })
          this.error = ''
          this.$router.replace('/dashboard')
          this.flashMessage.show({
            status: 'info',
            title: 'Signed In',
            message: 'Signin successful, welcome back!'
          })
        })
        .catch(error => this.signinFailed(error))
    },
    signinFailed (error) {
      this.user.error = (error.response && error.response.data && error.response.data.error)
      this.$store.commit('unsetCurrentUser')
    },
    checkSignedIn () {
      if (this.$store.state.signedIn) {
        this.$router.replace('/dashboard')
      }
    }
  }

This image displays the successful completion of the API call to sign in and the return of the user object: https://i.stack.imgur.com/Oab9W.png

Similarly, this image shows the Vue Panel setting the currentUser state with the user object: https://i.stack.imgur.com/FKP93.png

However, upon performing a page refresh or moving away from the dashboard, all data stored in the state gets lost.

https://i.stack.imgur.com/YJFwO.png

Given my limited experience with Vuex, I have attempted to utilize Vue.set and $set on my mutations in store.js, but this did not resolve the issue. Any suggestions or assistance would be greatly appreciated!

Below is my store.js file:

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    currentUser: {},
    signedIn: false,
    csrf: null
  },
  mutations: {
    setCurrentUser (state, { currentUser, csrf }) {
      state.currentUser = currentUser
      state.signedIn = true
      state.csrf = csrf
    },
    unsetCurrentUser (state) {
      state.currentUser = {}
      state.signedIn = false
      state.csrf = null
    },
    refresh (state, csrf) {
      state.signedIn = true
      state.csrf = csrf
    }
  },
  getters: {
    isOwner (state) {
      return state.currentUser && state.currentUser.role === 'owner'
    },
    isManager (state) {
      return state.currentUser && state.currentUser.role === 'manager'
    },
    isAdmin (state) {
      return state.currentUser && state.currentUser.role === 'admin'
    },
    isUser (state) {
      return state.currentUser && state.currentUser.role === 'user'
    },
    isSignedIn (state) {
      return state.signedIn === true
    }
  },
  plugins: [
    createPersistedState({

    })
  ]
})

Answer №1

Include the necessary plugins such as [createPersistedState()] during the initialization of the store instance

export default new Vuex.Store({
          plugins: [createPersistedState()],}

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

Step-by-step guide on loading and previewing a PDF file in an iframe using VUEX

I am currently working on my VUEJS app where I need to display a preview of a PDF file fetched from an API and stored in VUEX. However, I am facing issues with displaying the PDF preview. store/index.js export default new Vuex.Store({ state: () => ( ...

Tips for dynamically updating the value of a variable in Vue by importing a JavaScript file

There is a file for an app that imports ymaps.js where YmapsComponent.vue is declared. import '../js/ymaps.js'; import { createApp } from 'vue'; const app = createApp({}); import YmapsComponent from './components/YmapsComponent.vue ...

Guide to correcting Form Data errors with XHR resulting in a 400 Bad Request

This is a straightforward piece of code I've written. It's simply a POST request to my API endpoint using FormData. Interestingly, the API is returning a bad request error for reasons unknown to me. When I tested the API with curl, everything wo ...

The presence of #xfbml=1 is leading to some issues

Within my website, I am utilizing two distinct mechanisms incorporating both xfbml and fbjs: An FB:Like tag for individual entries The FB object for Facebook logins with FB connect The issue arises when "all.js" is included on the page, as the login scr ...

Struggling to access YouTube account via Google sign-in using Puppeteer framework

I am facing an issue with my puppeteer code where I am unable to proceed past the email page after clicking next due to some bot protection by Google advising me to "Try using a different browser...etc". Is there a way to bypass this using puppeteer? I h ...

Tips to successfully save and retrieve a state from storage

I've encountered a challenge while working on my Angular 14 and Ionic 6 app. I want to implement a "Welcome" screen that only appears the first time a user opens the app, and never again after that. I'm struggling to figure out how to save the s ...

Concealing a Vuejs dropdown when clicking outside of the component

I am currently working on a Vuejs project where I am creating a menu component. This menu consists of 2 dropdowns, and I have already implemented some methods and used Vue directives to ensure that when one dropdown is clicked, the other hides and vice ver ...

Guide to eliminating the clearable icon in the Vuetify file input

I am struggling to find any props to deactivate the clearable icon. Additionally, there doesn't seem to be an event related to this issue. Is there a method available to eliminate the clearable icon? <v-file-input ref="profilePictureFileInput" ...

Ways to ensure a function is only triggered once using onmouseover

I'm fairly new to JavaScript and I've been attempting to create a function that only runs once. Here's the logo I've been trying to animate: <img src="img/logot2.png" id="logoutjs" onmouseover="move()" ...

Error occurred while attempting to execute the method

Here's a MongoDB Mongoose query we're dealing with: sampleSchema.find({ $where: "expired <= " + (new Date()) }) .limit(9) // Problems may arise from here .sort({ postedDate: -1 }) .then((docs) => { console.log(&apos ...

Tone.js is failing to sync sequences during playback

I'm currently working on developing a sequencer using Tone.js. Right now, I have a basic sequence that plays when the user clicks the play button. However, I've encountered an issue where if the button is pressed to pause and then played again, t ...

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

Struggling to master YAML integration with Google App Engine?

Seeking assistance with YAML as I am new to it: application: baking-tutorial version: secureable runtime: python27 api_version: 1 threadsafe: true handlers: - url: /robots\.txt static_files: static/robots.txt upload: static/robots\.txt - url: ...

What advantages does the use of $(e).attr(name,value) offer compared to using e.setAttribute(name,value)?

Scenario: The variable "e" represents an element of type "HtmlElement" and not a "css selector" I am referring to any attribute, not just the standard allowed ones like "atom-type" or "data-atom-type". Regardless of the attribute name, will it function wi ...

What is the reason I am unable to upload personalized templates using <script> elements?

I have a dilemma where I need to swap out multiple templates from a library with my own custom ones without forking the original templates. When I include the templates in my index.html page like: <script type="text/ng-template" id="first-template"> ...

Unable to integrate multiple webpack projects: Uncaught SyntaxError occurs due to a missing closing parenthesis after the argument list

My website features a section where clients can track their projects. One aspect of the site involves viewing a blueprint created using THREE.js and bundled with webpack. I have been tasked with adding another type of blueprint to the site. I have success ...

Troubleshooting issue with jquery.i18n.properties functionality

I am encountering an issue with implementing jQuery internationalization. I have included the files jquery.i18n.properties.js, jquery.i18n.properties-min.js, and jquery-min.js in my resources folder. In my jsp, I have added the following code: <script ...

Deleting an added element upon closing the dialog box

Utilizing JQuery and Ajax, I successfully update my database. Following each update, a png icon is displayed briefly for 1 second. Specifically, the update form is contained within a JQuery dialog box. However, upon closing the dialog box after an update, ...

Transforming a datetime-local Element into a Date Object

I am currently utilizing the HTML5 element datetime-local with the requirement of having two different formats for the date. One format will be stored as a date object in the database, while the other format will be used as a string to set the datetime-loc ...

I came across a forum where someone mentioned encountering a similar issue but unfortunately, no solution was provided. Currently, I am working on setting up a reaction roles system but despite embedding the message, the role is not being

I am currently working on setting up a reaction roles system for my Discord server, but I have encountered a significant issue that may seem minor to most. The problem is that although my bot successfully sends embeds with corresponding emojis for the ro ...