NextAuth 사용중 새로고침을 하게되면 세션은 존재하는데 존재하는 세션에 관한 데이터를 사용하지 못하는 문제점이 발생되었다.
'use client';
import { Usertype } from '@/types/auth';
import { useSession } from 'next-auth/react';
import { useEffect, useState } from 'react';
import styles from '../_styles/Profile.module.css';
const Profile = () => {
const { data: session, status } = useSession();
// 세션이 로딩 될 때까지 로딩처리
const [profile, setProfile] = useState<Usertype>(null);
const fetchUserProfile = async (): Promise<void> => {
try {
const response = await fetch(`/api/profile/${session?.user.id}`, {
method: 'GET',
});
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const fetchData = await response.json();
console.log(fetchData);
setProfile(fetchData);
} catch (error: any) {
console.error(error.message);
}
};
useEffect(() => {
fetchUserProfile();
}, [session]);
if (status === 'loading') {
return <p>Loading...</p>;
}
return (
<div className={styles.container}>
<div className={styles['profile-header']}>프로필 관리</div>
<div>{profile?.email}</div>
</div>
);
};
export default Profile;
임시 방편으로 useEffect의 의존성배열에 session을 넣어놨지만 좋은 방식이 아닌 것 같다.
이렇게 사용하게되면 loading 상태를 걸어서 사용자에게 페이지를 제공하여야 한다.
두번째 방법으로 생각한것은 JWT Token을 cookie에 가져와서 사용하는 것이다. 그러나 cookie에 내가 필요한 정보를 전부 다 담을 수 있을지 의문이다. 두번째 방법으로 최대한 진행하여야 하지만 일단은 첫번째 방식으로 진행 할 예정이다.