From 64812a7f108b0a74dc29679ea8d21afaabecd0e7 Mon Sep 17 00:00:00 2001 From: seung365 Date: Thu, 8 Aug 2024 03:05:58 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20auth=20provider=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Provider/Auth.tsx | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/src/Provider/Auth.tsx b/src/Provider/Auth.tsx index d511896..7066fd9 100644 --- a/src/Provider/Auth.tsx +++ b/src/Provider/Auth.tsx @@ -1,35 +1,51 @@ import { AuthContextType, AuthInfo } from '@/types'; -import { createContext, useContext, useState, ReactNode, useEffect } from 'react'; +import { createContext, useContext, useState, ReactNode, useEffect, useCallback } from 'react'; export const AuthContext = createContext(undefined); export const AuthProvider = ({ children }: { children: ReactNode }) => { const [authInfo, setAuthInfo] = useState(undefined); - const updateAuthInfo = (auth: AuthInfo) => { - if (auth) { - setAuthInfo(auth); - } - }; + const updateAuthInfo = useCallback((auth: AuthInfo) => { + setAuthInfo((prevAuth) => { + if (JSON.stringify(prevAuth) !== JSON.stringify(auth)) { + return auth; + } + return prevAuth; + }); + }, []); - const handleAuthInfo = () => { + const handleAuthInfo = useCallback(() => { const authToken = sessionStorage.getItem('accessToken'); if (authToken) { const email = sessionStorage.getItem('email') || ''; const name = sessionStorage.getItem('name') || ''; const picture = sessionStorage.getItem('picture') || ''; - setAuthInfo({ + updateAuthInfo({ accessToken: authToken, - email: email, - name: name, - picture: picture, + email, + name, + picture, }); + } else { + setAuthInfo(undefined); } - }; + }, [updateAuthInfo]); useEffect(() => { handleAuthInfo(); - }); + + const handleStorageChange = (event: StorageEvent) => { + if (event.key === 'accessToken') { + handleAuthInfo(); + } + }; + + window.addEventListener('storage', handleStorageChange); + return () => { + window.removeEventListener('storage', handleStorageChange); + }; + }, [handleAuthInfo]); return ( {children}