SyntaxSquad/DADProject#9 feat: User info dysplayed in /users/
This commit is contained in:
+33
-14
@@ -1,39 +1,58 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { useAuthStore } from './auth'
|
||||
|
||||
export const useUserStore = defineStore('user', {
|
||||
state: () => ({
|
||||
user: null,
|
||||
token: localStorage.getItem('token') || null,
|
||||
loading: false,
|
||||
error: null
|
||||
}),
|
||||
|
||||
getters: {
|
||||
currentUser: (state) => state.user
|
||||
},
|
||||
|
||||
actions: {
|
||||
async fetchUser() {
|
||||
if (!this.token) return
|
||||
async fetchUserProfile() {
|
||||
const authStore = useAuthStore()
|
||||
const token = authStore.getToken()
|
||||
|
||||
if (!token) {
|
||||
this.error = 'No authentication token found'
|
||||
throw new Error('No authentication token found')
|
||||
}
|
||||
|
||||
this.loading = true
|
||||
this.error = null
|
||||
|
||||
try {
|
||||
const response = await axios.get('/api/users/me', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
this.user = response.data
|
||||
return response.data
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch user")
|
||||
this.error = error.response?.data?.message || 'Failed to fetch user profile'
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
authStore.logout()
|
||||
}
|
||||
|
||||
throw error
|
||||
} finally {
|
||||
this.loading = false
|
||||
}
|
||||
},
|
||||
|
||||
setToken(token) {
|
||||
this.token = token
|
||||
localStorage.setItem('token', token)
|
||||
},
|
||||
|
||||
logout() {
|
||||
this.token = null
|
||||
clearUser() {
|
||||
this.user = null
|
||||
localStorage.removeItem('token')
|
||||
this.error = null
|
||||
this.loading = false
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user