Skip to content

Instantly share code, notes, and snippets.

@michaeltcoelho
Last active February 21, 2019 23:44
Show Gist options
  • Save michaeltcoelho/9330d2a3ecaf485a3d61e36aead951c6 to your computer and use it in GitHub Desktop.
Save michaeltcoelho/9330d2a3ecaf485a3d61e36aead951c6 to your computer and use it in GitHub Desktop.
// auth.js in nuxtjs/store
export const state = () => {
return {
session: {
user: null,
token: null
}
}
}
export const mutations = {
SET_TOKEN(state, token) {
state.session.token = token
},
SET_CURRENT_USER(state, user) {
state.session.user = user
}
}
export const actions = {
async nuxtServerInit({ dispatch }, { req }) {
const token = getTokenFromCookie(req)
if (token) {
await dispatch('refreshSession', { token })
}
},
setToken({ commit }, token) {
Cookie.set('token', token)
commit('SET_TOKEN', token)
this.$axios.setToken(token, 'Token')
},
me({ commit }) {
this.$axios
.get('/auth/me')
.then(({ data }) => {
commit('SET_CURRENT_USER', data)
})
.catch(err => {
console.log(err)
})
},
refreshSession({ dispatch }, { token }) {
dispatch('setToken', token)
dispatch('me')
},
}
// index.js in nuxtjs/store
export const actions = {
async nuxtServerInit({ dispatch }, context) {
await dispatch('auth/nuxtServerInit', context)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment