Why I can't save Vuex states with vuex-persistedstate and js-cookie? - vuex

I'm trying to save Vuex states inside Cookies as I see in the documentation. js-cookies and vuex-persistedstate are imported this way:
import createPersistedState from 'vuex-persistedstate'
import Cookies from 'js-cookie'
Saving the states inside LocalStorage works fine:
const store = new Vuex.Store({
state: {
},
mutations: {
},
getters: {
},
modules: {
user,
register,
auth,
},
plugins: [createPersistedState()]
})
Trying to save the states in the Cookies I get no Vuex value:
const store = new Vuex.Store({
state: {
},
mutations: {
},
getters: {
},
modules: {
user,
register,
auth,
},
plugins: [createPersistedState({
storage: {
getItem: key => Cookies.get(key),
// Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
setItem: (key, value) => Cookies.set(y, value, { expires: 3, secure: true }),
removeItem: key => Cookies.remove(key)
}
}
)]
})
Later edit
Using vuex-persist package all works as expected!
const vuexCookie = new VuexPersistence({
restoreState: (key, storage) => Cookies.getJSON(key),
saveState: (key, state, storage) =>
Cookies.set(key, state, {
expires: 3
})
})
// Store
const store = new Vuex.Store({
state: {
},
mutations: {
},
getters: {
},
modules: {
chestionare,
user,
register,
auth,
},
plugins: [vuexCookie.plugin]
})

Try to change this:
[createPersistedState({
storage: {
getItem: key => Cookies.get(key),
// Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
setItem: (key, value) => Cookies.set(y, value, { expires: 3, secure: true }),
removeItem: key => Cookies.remove(key)
}
}
)]
To this:
[createPersistedState({
key: 'your_key',
storage: {
getItem: (key) => JSON.parse(Cookies.get(key)),
setItem: (key, value) => Cookies.set(key, JSON.stringify(value), {expires: 3, secure: true}),
removeItem: (key) => Cookies.remove(key)
}
})]

Related

vuex "url" of undefined using axios

I've recently learnt a bit about vuex and store.
I was about to use it for calling my api but it keeps saying my
url is undefined.
here is my vuex codes:
import { createStore } from 'vuex'
import axios from "axios";
const url = 'https://myurl'
export default createStore({
state: {
catList: [],
transactList: [],
user: [],
requestList: [],
catInList: [],
productList: [],
errorMs: '',
calling: false,
mobile: ''
},
getters: {
allUsers: (state) => state.user,
transactList: (state) => state.transactList,
categoryList: (state) => state.catList,
requestList: (state) => state.requestList,
productList: (state) => state.productList,
},
mutations: {
SET_Users (state, user) {
state.user = user
}
},
actions: {
checkAuth() {
const token = localStorage.getItem('token') ? localStorage.getItem('token') : ''
axios.defaults.baseURL = url
axios.defaults.headers.common['Authorization'] = token ? `Bearer ${token}` : ''
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
},
async axiosPost ({dispatch} ,{url}) {
dispatch('checkAuth')
await axios.post(url+'/login', {
mobile: this.mobile
}).then(response => {
this.calling = false
localStorage.setItem('token', response.data.token)
})
},
async axiosGet ({dispatch} , {url, formData}) {
dispatch('checkAuth')
await axios.get(url, formData).catch(err => {
console.log(err)
})
}
},
created() {
}
})
actually I wanted to define my api globally, so that I can use it for different components only by adding url + '/login' but I'm not sure why it keeps saying my url is not defined.
can anyone help me with the errors?

loggedIn state reverts back to false after Logging in and doesn't allow me to guard route

I'm trying to guard my routes with state: { loggedIn: false }, when I login from my Login.vue component the goal is to trigger an action this.$store.dispatch('setLogin') that mutates the state of loggedIn to true. There is then navigation guard that is suppose to prevent me form seeing my Login.vue and Regester.vue components. The problem is that it seems like the state changes to true, but not the base state: allowing me to keep hitting the /auth/login and /auth/register routes.
Routes
const routes = [
{
path: '/auth',
name: 'auth',
component: Auth,
children: [
{ name: 'login', path: 'login', component: Login },
{ name: 'register', path: 'register', component: Register },
],
meta: {
requiresVisitor: true,
}
},
{
path: '/logout',
name: 'logout',
component: Logout
}
]
Login Component
login() {
this.$http.get('/sanctum/csrf-cookie').then(response => {
this.$http.post('/login', {
email: this.username,
password: this.password,
}).then(response2 => {
this.$store.dispatch('setLogin')
this.$store.dispatch('getUser')
alert(this.$store.state.loggedIn)
this.$router.push({ name: 'Home' })
}).catch(error => {
console.log(error.response.data);
const key = Object.keys(error.response.data.errors)[0]
this.errorMessage = error.response.data.errors[key][0]
})
});
}
Vuex
export default new Vuex.Store({
state: {
loggedIn: false,
user: JSON.parse(localStorage.getItem('user')) || null,
},
mutations: {
setLogin: (state) => {
state.loggedIn = true
},
SET_USER_DATA (state, userData) {
localStorage.setItem('user', JSON.stringify(userData))
state.user = userData;
},
removeUser(state) {
localStorage.removeItem('user');
state.user = null;
}
},
actions: {
getUser(context) {
if (context.state.loggedIn) {
alert('hit');
return new Promise((resolve, reject) => {
axios.get('api/user')
.then(response => {
context.commit('SET_USER_DATA', response.data.data)
resolve(response)
})
.catch(error => {
reject(error)
})
})
}
},
setLogin(context){
context.commit('setLogin')
}
},
modules: {
}
})
It's strange because alert(this.$store.state.loggedIn) renders true, but when I go back the auth link there's a mounted state alert that comes back false.
Here's my navigation guards as well:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.state.loggedIn) {
next({
name: 'login',
})
} else {
next()
}
} else if (to.matched.some(record => record.meta.requiresVisitor)) {
if (store.state.loggedIn) {
next({
name: 'Home',
})
return
} else {
next()
}
} else {
next()
}
})
You need to store the loggedIn user in local storage:
setLogin: (state) => {
state.loggedIn = localStorage.setItem('loggedIn', 'true')
state.loggedIn = true
},
Then your state should look like:
state: {
loggedIn: localStorage.getItem('loggedIn') || null,
},

How to use createPersistedState in a vuex and quasar application?

How to use createPersistedState in a vuex and quasar application?
I am trying to persist some daos in the cookie of my application, however the data is not being written in the cookie.
What am I doing wrong?
Thank you in advance for your attention of all.
Action
function setUser ({ commit }) {
axios.get(`/modulo/app`, { headers: { 'Authorization': 'Bearer ' + store.getters.getToken() } })
.then(response => {
commit('setUserMutation', response.data)
})
.catch(error => {
if (!error.response) {
console.log(error.response)
}
})
}
Mutation
const setUserMutation = (state, data) => { state.user = data }
Getters
function getUser (state) {
return state.user
}
index config Store
export default function () {
const Store = new Vuex.Store({
modules: {
auth
},
plugins: [createPersistedState(
{
paths: ['auth.setUserMutation'],
storage: {
getItem: key => Cookies.get(key),
setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }),
removeItem: key => Cookies.remove(key)
}
}
)],
strict: process.env.DEV
})
return Store
}
most likely it's due to the secure props you use in Cookie.set
secure
Either true or false, indicating if the cookie transmission requires a secure protocol (https).
-https://github.com/js-cookie/js-cookie
If you are developing on localhost, it most likely is not using HTTPS.
You can set the secure value to be based on your environment, by using env variable
secure: process.env.NODE_ENV === 'production'

How do I use Vue.set() properly?

I am trying to make an array within my store reactive.
I have currently tried using :key to force update, $forceUpdate() and Vue.set(). I originally was getting and updating the data within the calendar component, but I moved the get data logic to the store in hopes that somehow it would make it reactive. The current attribute shows a red dot on the prescribed v-calendar date. From what I can tell the array is populating with objects with the exact same structure as the single attribute, but it is not reactive.
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
loading: true,
odata: [],
attributes: [{
dates: new Date(),
dot: 'red',
customdata: {
programEventsSystemrecordID: 1234
}
}]
},
mutations: {
updateAtts (state) {
let singleAtt = {}
let index = 0
state.odata.forEach((ticket) => {
Vue.set(singleAtt, 'dot', 'red')
Vue.set(singleAtt, 'dates', new Date(ticket.ProgramEventsStartdate))
Vue.set(singleAtt, 'customData', {})
singleAtt.customData = {
programEventsSystemrecordID: ticket.ProgramEventsSystemrecordID
}
Vue.set(state.attributes, index, singleAtt)
index++
})
},
updateOdata (state, odata) {
state.odata = odata
},
changeLoadingState (state, loading) {
state.loading = loading
}
},
actions: {
loadData ({ commit }) {
axios.get('https://blackbaud-odata-cal-bizcswpdjy.now.sh')
.then((response) => {
commit('updateOdata', response.data)
})
.catch((err) => {
console.log(err)
})
.finally(() => {
console.log(commit('updateAtts'))
commit('changeLoadingState', false)
})
}
}
})
I expect the array that is being populated within vue to update the DOM. There are no error messages.
Vue.set is useless in your case. In mostly all cases, it's useless.
It's needed to add new properties in the state that where not initially.
Here, you just have one state property that is build from another.
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
loading: true,
odata: [],
attributes: [{
dates: new Date(),
dot: 'red',
customdata: {
programEventsSystemrecordID: 1234
}
}]
},
mutations: {
updateAtts (state) {
state.attributes = state.odata.map(t=>({
dot: 'red',
dates: new Date(t.ProgramEventsStartdate),
customData: {programEventsSystemrecordID: t.ProgramEventsSystemrecordID}
}))
},
updateOdata (state, odata) {
state.odata = odata
},
changeLoadingState (state, loading) {
state.loading = loading
}
},
actions: {
loadData ({ commit }) {
axios.get('https://blackbaud-odata-cal-bizcswpdjy.now.sh')
.then((response) => {
commit('updateOdata', response.data)
})
.catch((err) => {
console.log(err)
})
.finally(() => {
console.log(commit('updateAtts'))
commit('changeLoadingState', false)
})
}
}
})

Nuxt Auth Module Authenticated User Data

I have an API api/auth that is used to log users in. It expects to receive an access_token (as URL query, from Headers, or from request body), a username, and a password. I've been using the Vue Chrome Developer Tool and even though I get a 201 response from the server, the auth.loggedIn state is still false. I think that might be the reason why my redirect paths on the nuxt.config.js isn't working as well. Can anyone point me to the right direction on why it doesn't work?
This is a screenshot of the Vue Chrome Developer Tool
This is the JSON response of the server after logging in. The token here is different from the access_token as noted above.
{
"token": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"user": {
"user_name": "xxxxxxxxxxxxxxxxxx",
"uid": "xxxxxxxxxxxxxxxxxx",
"user_data": "XXXXXXXXXXXXXXXXXXXXXXXXX"
}
}
Here is the relevant part of nuxt.config.js
export default {
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth',
['bootstrap-vue/nuxt', { css: false }]
],
router: {
middleware: [ 'auth' ]
},
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/api/auth?access_token=XXXXXXXXXXXXXXXXXXXXXX',
method: 'post',
propertyName: 'token'
},
logout: {
url: '/api/auth/logout',
method: 'post'
},
user: {
url: '/api/users/me',
method: 'get',
propertyName: 'user'
}
}
}
},
redirect: {
login: '/',
logout: '/',
home: '/home'
},
token: {
name: 'token'
},
cookie: {
name: 'token'
},
rewriteRedirects: true
},
axios: {
baseURL: 'http://localhost:9000/'
}
}
And my store/index.js
export const state = () => ({
authUser: null
})
export const mutations = {
SET_USER: function (state, user) {
state.authUser = user
}
}
export const actions = {
nuxtServerInit ({ commit }, { req }) {
if (req.session && req.user) {
commit('SET_USER', req.user)
}
},
async login ({ commit }, { username, password }) {
const auth = {
username: username,
password: password
}
try {
const { user } = this.$auth.loginWith('local', { auth })
commit('SET_USER', user)
} catch (err) {
console.error(err)
}
}
}
The login action in the store is triggered by this method in the page:
export default {
auth: false,
methods: {
async login () {
try {
await this.$store.dispatch('login', {
username: this.form.email,
password: this.form.password
})
} catch (err) {
this.alert.status = true
this.alert.type = 'danger'
this.alert.response = err
}
}
}
}
P.S. I realize I'm explicitly including the access_token in the URL. Currently, I don't know where a master_key or the like can be set in the Nuxt Auth Module.
Try this in your store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = () => new Vuex.Store({
state: {
authUser: null
},
mutations: {
SET_USER: function (state, user) {
state.authUser = user
}
},
actions: {
CHECK_AUTH: function(token, router) {
if (token === null) {
router.push('/login')
}
}
}
})
export default store
And for the router, this should work globally:
$nuxt._router.push('/')