I have been working with Nuxt.js and have been trying to create my own authentication system. Everything seems to be functioning correctly, but whenever I refresh the page, the state reverts back to its initial data. To address this issue, I attempted to initialize the Vuex store using localStorage in the following manner:
export const state = () => ({
status: '',
token: localStorage.getItem('token') || '',
loggedInUser: localStorage.getItem('user') || '',
})
However, I encountered an error stating
localStorage is not defined
, even though localStorage.setItem
works without any issues in the actions.
Below is the complete code snippet:
import axios from 'axios'
export const state = () => ({
status: '',
token: localStorage.getItem('token') || '',
loggedInUser: localStorage.getItem('user') || '',
})
export const getters = {
status (state) {
return state.status
},
authenticated (state) {
return !!state.token
},
token (state) {
return state.token
},
loggedInUser (state) {
return state.loggedInUser
},
}
export const mutations = {
auth_request(state) {
state.status = 'loading'
},
auth_success(state, token) {
state.status = 'success'
state.token = token
},
auth_error(state) {
state.status = 'error'
},
logout(state) {
state.status = ''
state.token = ''
state.loggedInUser = {}
},
auth_success2 (state, loggedInUser) {
state.loggedInUser = Object.assign({}, loggedInUser)
}
}
export const actions = {
login({commit}, data) {
return new Promise((resolve, reject) => {
commit('auth_request')
axios.post('http://127.0.0.1:8000/api/login', data)
.then((res) => {
const loggedInUser = Object.assign({}, res.data.data)
const token = res.data.meta.token
localStorage.setItem('token', token)
localStorage.setItem('user', loggedInUser.name)
axios.defaults.headers.common['Authorization'] = 'Bearer '+ token
commit('auth_success', token)
commit('auth_success2', loggedInUser)
this.$router.push('/')
resolve(res)
})
.catch((error) => {
commit('auth_error')
console.log(error)
reject(error)
})
})
}
}