SyntaxSquad/DADProject#9 feat: User info dysplayed in /users/

This commit is contained in:
2025-12-18 21:04:49 +00:00
parent 94fdbd568c
commit d1dd2c00f6
7 changed files with 305 additions and 93 deletions
+33 -14
View File
@@ -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
}
}
})