Ziya/app/stores/app.ts

99 lines
No EOL
2.3 KiB
TypeScript

export const useAppStore = defineStore('app', () => {
// State
const isLoading = ref(false)
const currentUser = ref<{ name: string; email: string } | null>(null)
const appVersion = ref('1.0.0')
// Getters
const isAuthenticated = computed(() => currentUser.value !== null)
const userInitials = computed(() => {
if (!currentUser.value) return '??'
return currentUser.value.name
.split(' ')
.map(n => n[0])
.join('')
.toUpperCase()
})
// Actions
const setLoading = (loading: boolean) => {
isLoading.value = loading
}
const login = async (email: string, password: string) => {
setLoading(true)
try {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000))
// Mock user data
currentUser.value = {
name: 'John Trader',
email: email
}
console.log('Welcome back!')
return true
} catch (error) {
console.log('Login failed. Please try again.')
return false
} finally {
setLoading(false)
}
}
const logout = async () => {
setLoading(true)
try {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 500))
currentUser.value = null
console.log('You have been logged out')
} finally {
setLoading(false)
}
}
// Persist user data to localStorage
watch(currentUser, (newUser) => {
if (newUser) {
localStorage.setItem('ziya-user', JSON.stringify(newUser))
} else {
localStorage.removeItem('ziya-user')
}
})
// Initialize from localStorage
const initializeFromStorage = () => {
if (process.client) {
const storedUser = localStorage.getItem('ziya-user')
if (storedUser) {
try {
currentUser.value = JSON.parse(storedUser)
} catch (error) {
console.error('Failed to parse stored user data:', error)
localStorage.removeItem('ziya-user')
}
}
}
}
return {
// State
isLoading: readonly(isLoading),
currentUser: readonly(currentUser),
appVersion: readonly(appVersion),
// Getters
isAuthenticated,
userInitials,
// Actions
setLoading,
login,
logout,
initializeFromStorage
}
})