I have never used Vuex
with Nuxt.js
, so I have met the problem. Here is my store/index.js
file:
export const state = () => ({
wrongCredentials: false,
logged: false,
uxd: null
})
export const mutations = {
setWrongCredentials(state, value) {
state.wrongCredentials = value
},
setLogged(state, value) {
state.logged = value
},
setUxd(state, value) {
state.uxd = value
},
}
As you can see there is state and mutations. In my other file, where I check user's JWT token and, depending on resultM I want set values in store:
import jwt from 'jsonwebtoken'
import cert from '../jwt/public'
export default {
verify (token) {
jwt.verify(token, cert, async (err, decoded) => {
if (err) {
this.$store.state.wrongCredentials = true
this.$store.state.logged = false
this.$store.state.uxd = null
} else {
this.$store.state.wrongCredentials = false
this.$store.state.logged = true
this.$store.state.uxd = decoded.uxd
}
})
}
}
The code you see doesn't work correctly, it just doesn't set values, so, I have created mutations and did something like this:
await this.$store.dispatch('setWrongCredentials', true)
Also doesn't work. The problem is, I don't know how to work with Vuex
store not in .vue
files, so, how can I set values in store?
CodePudding user response:
Unfortunately, I have not found solution of this problem like I wanted in .js
file, so, here is another solution.
First of all, you need to set no only state and mutations, but also actions:
export const actions = {
fetchWrongCredentials(ctx, value) {
ctx.commit('setWrongCredentials', value)
},
fetchLogged(ctx, value) {
ctx.commit('setLogged', value)
},
fetchUxd(ctx, value) {
ctx.commit('setUxd', value)
}
}
And in your Vue
component you need to set values in state using actions, just like that:
methods: {
...mapActions(['fetchWrongCredentials', 'fetchLogged', 'fetchUxd']),
async login() {
await login({
password: this.userPassword,
login: this.userLogin,
twoFactor: this.twoFactor
}).then(result => {
const jwtRes = jwt.verify(result.token)
this.fetchLogged(true)
this.fetchWrongCredentials(false)
this.fetchUxd(jwtRes.token)
}).catch(() => {
this.fetchLogged(false)
this.fetchWrongCredentials(true)
this.fetchUxd(null)
this.error = true
setTimeout(() => {
this.error = false
}, 1000)
})
}
}
In my case, I had to modify that .js
file:
import jwt from 'jsonwebtoken'
import cert from '../jwt/public'
export default {
verify (token) {
return jwt.verify(token, cert, (err, decoded) => {
if (err) {
return false
} else {
return { token: decoded.uxd }
}
})
}
}