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.