Files
auto-trade/stores/auth-store.ts

80 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

import { create } from "zustand";
import { persist } from "zustand/middleware";
/**
* [ ]
*/
export interface User {
id: string;
email: string;
name?: string;
avatar?: string;
createdAt?: string;
}
/**
* [ ]
*/
interface AuthState {
// ========== 상태 ==========
user: User | null;
isAuthenticated: boolean;
// ========== 액션 ==========
setUser: (user: User | null) => void;
updateUser: (updates: Partial<User>) => void;
logout: () => void;
}
/**
* [ ]
*
* .
* - localStorage에 (persist )
* -
*
* @example
* ```tsx
* import { useAuthStore } from '@/stores/auth-store';
*
* function Profile() {
* const { user, isAuthenticated, setUser } = useAuthStore();
*
* if (!isAuthenticated) return <Login />;
* return <div>Welcome, {user?.email}</div>;
* }
* ```
*/
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
// ========== 초기 상태 ==========
user: null,
isAuthenticated: false,
// ========== 사용자 설정 ==========
setUser: (user) =>
set({
user,
isAuthenticated: !!user,
}),
// ========== 사용자 정보 업데이트 ==========
updateUser: (updates) =>
set((state) => ({
user: state.user ? { ...state.user, ...updates } : null,
})),
// ========== 로그아웃 ==========
logout: () =>
set({
user: null,
isAuthenticated: false,
}),
}),
{
name: "auth-storage", // localStorage 키 이름
},
),
);