monolito_djanco_poonto/store/index.js
Thaís Ferreira f3317dc54f 11h33
2025-01-30 11:33:58 -03:00

55 lines
1.3 KiB
JavaScript

import Vue from 'vue'
import Vuex from 'vuex'
import { authService } from '@/services/api'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
user: null,
token: localStorage.getItem('token') || null,
loading: false,
error: null
},
mutations: {
SET_USER(state, user) {
state.user = user
},
SET_TOKEN(state, token) {
state.token = token
},
SET_LOADING(state, loading) {
state.loading = loading
},
SET_ERROR(state, error) {
state.error = error
}
},
actions: {
async login({ commit }, credentials) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
const response = await authService.login(credentials)
commit('SET_TOKEN', response.token)
localStorage.setItem('token', response.token)
} catch (error) {
commit('SET_ERROR', error.message)
throw error
} finally {
commit('SET_LOADING', false)
}
},
logout({ commit }) {
commit('SET_USER', null)
commit('SET_TOKEN', null)
localStorage.removeItem('token')
}
},
getters: {
isAuthenticated: state => !!state.token,
currentUser: state => state.user,
isLoading: state => state.loading,
error: state => state.error
}
})