1+ import { LS_KEY_ACCESS_TOKEN } from "@/constants/ls-key.constant" ;
2+ import { useAuthStore } from "@/features/auth/store" ;
13import { IUser } from "@/types/user" ;
24import { useMutation , useQuery , useQueryClient } from "@tanstack/react-query" ;
3- import { createContext , ReactNode , use , useCallback , useMemo } from "react" ;
4- import { getProfileApi } from "./apis/auth.api" ;
5-
6- import { LS_KEY_ACCESS_TOKEN } from "@/constants/ls-key.constant" ;
5+ import { useEffect } from "react" ;
6+ import { getProfileApi } from "../apis/auth.api" ;
77
88type LoginFn = ( ) => Promise < { token : string } > ;
99
10- export interface AuthContextType {
11- user : IUser | null ;
12- isLoading : boolean ;
13- refreshUser : ( ) => void ;
14- login : ( fn : LoginFn ) => Promise < void > ;
15- logout : ( ) => void ;
16- }
17-
18- export const AuthContext = createContext < AuthContextType | undefined > ( undefined ) ;
19-
20- export function AuthProvider ( { children } : { children : ReactNode } ) {
10+ export function useAuth ( ) {
2111 const queryClient = useQueryClient ( ) ;
12+ const { setUser, setIsLoading } = useAuthStore ( ) ;
2213
2314 const {
2415 data : user ,
@@ -36,6 +27,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
3627 initialData : null ,
3728 } ) ;
3829
30+ // Sync user data with Zustand store
31+ useEffect ( ( ) => {
32+ setUser ( user ) ;
33+ } , [ user , setUser ] ) ;
34+
35+ // Sync loading state with Zustand store
36+ useEffect ( ( ) => {
37+ setIsLoading ( isLoading ) ;
38+ } , [ isLoading , setIsLoading ] ) ;
39+
3940 const { mutateAsync : login } = useMutation ( {
4041 mutationFn : async ( fn : LoginFn ) => {
4142 const { token } = await fn ( ) ;
@@ -47,33 +48,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
4748 } ,
4849 } ) ;
4950
50- const logout = useCallback ( ( ) => {
51+ const logout = ( ) => {
5152 localStorage . removeItem ( LS_KEY_ACCESS_TOKEN ) ;
5253 queryClient . setQueryData ( [ "profile" ] , null ) ;
53- } , [ queryClient ] ) ;
54-
55- const authContextValue = useMemo < AuthContextType > (
56- ( ) => ( {
57- user,
58- isLoading,
59- refreshUser,
60- login,
61- logout,
62- } ) ,
63- [ user , isLoading , refreshUser , login , logout ] ,
64- ) ;
65-
66- return (
67- < AuthContext value = { authContextValue } >
68- { children }
69- </ AuthContext >
70- ) ;
71- } ;
72-
73- export function useAuth ( ) {
74- const context = use ( AuthContext ) ;
75- if ( ! context ) {
76- throw new Error ( "useAuth must be used within an AuthProvider" ) ;
77- }
78- return context ;
54+ setUser ( null ) ;
55+ } ;
56+
57+ return {
58+ login,
59+ logout,
60+ refreshUser,
61+ } ;
7962}
0 commit comments