Skip to content

Commit

Permalink
Merge pull request #79 from Beside-Potenday/seungbeom
Browse files Browse the repository at this point in the history
authprovider 수정
  • Loading branch information
seung365 authored Aug 7, 2024
2 parents 702a3c6 + c63d00f commit 4feba39
Showing 1 changed file with 29 additions and 13 deletions.
42 changes: 29 additions & 13 deletions src/Provider/Auth.tsx
Original file line number Diff line number Diff line change
@@ -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<AuthContextType | undefined>(undefined);

export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [authInfo, setAuthInfo] = useState<AuthInfo | undefined>(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 (
<AuthContext.Provider value={{ authInfo, updateAuthInfo }}>{children}</AuthContext.Provider>
Expand Down

0 comments on commit 4feba39

Please sign in to comment.