topic concerning the interaction between vuex store and cookies

As I work on developing a Single Page Application, I've encountered an issue involving the interaction between vuex store and cookies (specifically vue-cookies). Upon a user login, the code below is executed:

this.$cookies.set('username', 'player1', '1h');
this.$store.commit('logIn');

The store configuration is as follows:

store: {
    username: window.$cookies.get('username') || null;
}

Here are the mutations:

logIn (state) {
  this.state.username = window.$cookies.get('username');
}

Once the user successfully logs in, the username is stored in the vuex store. However, a problem arises when the cookies expire, as the vuex store does not automatically remove the username. Any solutions on how to have the username removed from the store when the cookies expire?

Answer №1

If a user is no longer logged in or authenticated, you can simply set the username in the store to '' as needed.

Concerning my earlier comment, here is a snippet of code for reference.

Have you considered integrating authentication mechanisms into your application? One approach is to handle unauthenticated scenarios by implementing authentication logic to clear cookies or cached login data. In one project, we used an auth.js store module for managing authentication.

While this method may not directly address automatically removing stored items after a specified time, it ensures that the stored value is cleared when the cookie expires or is deleted, although it has not been tested.

Main app / calling store module

const store = new Vuex.Store({
    modules: {
      auth
    }
})

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})


<script>
import Vue from 'vue'
import { mapGetters } from 'vuex'
export default {
    name: "app",
    mounted() {
        let username = 'player1';
        this.$store.dispatch("LOGIN", username);
      }
}
</script>

store/auth.js module

const state = { 
    username: {},
    isautheticated: {}
}

const getters = {
    username: state => state.username,
    isautheticated: state => state.isautheticated,
}

const mutations = {
    SET_USERNAME: function(state, username){
        state.username = username;
    },
    SET_ISAUTHENTICATED: function(state, isautheticated){
        state.isautheticated = isautheticated;
    },
}

const actions = {
    LOGIN: ({commit, dispatch}, username) => {
        if (!window.$cookies.get('username')) {
            //not logged in, create cookie based on username

            //save username in store by committing a mutation
            commit(SET_USERNAME, username);
        } 
    },
    LOGOUT: ({commit, dispatch}) => {
        //remove cookie
        //window.$cookies.remove('username')

        //clear username
        commit(SET_USERNAME, '');
    },
    IS_AUTHENTICATED: ({commit, dispatch}) =>
    {
        //loop into your authentication module and clear the cookie if user becomes unauthenticated
        //added an arbitrary isautheticated value to the store for an example
        if(!state.isautheticated) {
            commit(SET_USERNAME, '');
        }
    }
}

export default {
    getters,
    mutations,
    actions,
    state
}

While including this logic in the store's LOGIN action may be excessive if no service calls for authentication or user data retrieval are made.

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

Using the useState Hook: What is the best way to add a new item to the end of an array stored in the state

I'm currently working on a project using Next.js and Tailwind, where I am trying to populate an array using the useState Hook. My intention is to iterate through the array using the map function and add items to the end of the array until there are n ...

Is there a way to automatically refresh a webpage whenever there are changes

Currently, I have a webpage that operates like a reverse auction, complete with a javascript countdown timer that tracks the time remaining in the auction. Once the timer reaches zero, the auction ends and the page automatically refreshes. While everythin ...

Issue with BootstrapVue b-table: selected rows are not saved when moving between pages with b-pagination

I implemented a b-table along with b-pagination in my Vue template: <b-table bordered hover responsive :items="items" :fields="fields" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc" sort-icon-le ...

The function to focus on this.$refs[("p" + index)] element is not available

I need help transforming a div into an input box when clicked, allowing me to edit the post inside a loop. Here is the button found on the post: <a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a> And here is the spec ...

Hiding rows in a Datatable

Assistance needed to conceal specific rows in the datatable, If the User opts for "Show All" from the dropdown menu, the entire datatable should be displayed, However, if the User chooses "Hide USA", I wish to hide the rows with the Country value set ...

In the event that the $state cannot be located, redirect to a different URL using Ui

Our platform is a unique combination of WordPress backend and AngularJS frontend, utilizing ui.router with html5 mode turned on and a base href="/" due to the stack sites being in the root of the site. We are currently facing an issue: 1) Previously, whe ...

How to display specific JSON objects that meet particular criteria in HTML cards using Ionic and Angular?

As a beginner in Ionic/Angular, I am attempting to fetch data from a JSON file and display it using cards in the HTML. The JSON contains numerous objects that are either marked as "deTurno == true" or "deTurno == false". Here is what I have so far: publi ...

My goal is to generate four HTML buttons that trigger specific functions: addition, subtraction, multiplication, and division

I am currently learning JavaScript, and I am facing some challenges with my assignment. The task is to create four buttons in HTML that trigger different functions - addition, subtraction, multiplication, and division. The goal is for the user to input two ...

Loading data with limit offset in AngularJS can lead to controller functions crashing and causing data to become jammed

I have developed a video gallery application similar to Youtube using AngularJS. The application includes a REST API which is accessed through Angular services. There are two controller files in the application with similar functionalities but calling diff ...

ReactJS: The function .useSelector() is not defined

I've been following a tutorial for a while and hit a roadblock trying to understand this. Both metaphorically and literally. On the Dashboard page, I attempted to use useSelector() to access the state of the goalSlice component. This component is ver ...

Convert JSON data into the desired format

My JSON input is as follows: [ { "date": { "value": "2022-05-01" }, "parent": { "value": "Choclate" }, ...

Submitting forms from a different router in React can pose a unique challenge

As a beginner in React, I am working on creating a simple meal app. In my App component, I am fetching meal data from an api and allowing users to click on a meal for more details. However, I am facing an issue where searching for a new meal on the detail ...

Expanding the Number of Arguments Sent to a Callback Function

I have a scenario where I am using a method that sends a POST request and then triggers a specific callback function to manage the response: myService.verify(id, verificationCallback); function verificationCallback(err, response) { ... } My query is two ...

Retrieve user input from an HTML form and pass it as a parameter in a jQuery AJAX request

Is there a way to pass a value from a user input in an HTML file to jQuery.ajax? Take a look at the code snippet from my JS file: jQuery(document).ready(function() { jQuery.ajax({ type: 'POST', url: 'myurl.asp ...

Use bracket notation to verify if a property is undefined

Having some difficulty determining if the property value of an object is undefined when accessed dynamically with bracket notation. Here's a snippet of my code: function toBritishDate(date: Date | string): string { console.log(date) return &qu ...

execute an action in the controller with the help of JavaScript and refresh the view

My scenario involves having multiple selects such as brands and products. I aim to dynamically update the products options based on the brand selected by the user. The select element looks like this: <select asp-for="Product.BrandId" class=&qu ...

Comparing the use of jQuery click event with the button to trigger a function that calculates the

Currently, I am grappling with a JQuery function that checks if any checkboxes are ticked within my form. My version of JQuery is v1.10.2. The code functions as expected when triggered by a button, but when I attempt to trigger it with a checkbox within t ...

The URL for this page is not within the app's designated domains and will not open Facebook Dialogs (FB UI)

I am currently working on integrating Facebook UI Dialogs into my website. My goal is to add custom actions when users share a post from my site. I have created my app, added the app URL and domain (which is the same as the URL), and included all necessa ...

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

Instructions for implementing a Back button that takes you directly to the text or link you clicked on to view an image

My goal is to have multiple anchor links within text, each linking to a specific image on the same page. Once the user views the image, I want them to be able to click a 'Back' button that will take them back to where they left off in the text. ...