I wrote the code so that the login data is stored in state, printed as console.log under the name UserImpL, and the Google login information of the login data is displayed.(displayName, photoUrl this two data)
However, when you refresh, the login data remains, but the photo and name you created on the Login Header disappear
I wrote the code to expose the picture and name when the login data exists, but I don t know why it disappeared.
Is the code wrong?
Login Header of Top
export default function Login() {
const [userData, setUserData] = useState(null);
const navigate = useNavigate();
const handleGoogleLogin = () => {
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider).then((data) => {
setUserData(data.user);
console.log(data);
});
};
//
const handleCart = () =>
onAuthStateChanged(auth, (user) => {
user != null ? navigate("/carts") : alert("로그인 해주세요.");
});
const handleGoogleLogOut = () => {
const auth = getAuth();
signOut(auth);
setUserData(null);
navigate("/");
};
const handleNewProduct = () => {
navigate("/products/new");
};
return (
<div>
{userData ? (
userData.email === "whiteforcoding@gmail.com" ? (
<div className="flex items-center">
<button onClick={handleNewProduct}>
<BsPencilFill />
</button>
<img
src={userData.photoURL}
alt={userData.displayName}
className="w-9 ml-4 mr-2 rounded-full"
/>
<p className="mr-4">{`${userData && userData.displayName} 님`}</p>
<button onClick={handleGoogleLogOut}>Logout</button>
</div>
) : (
<div className="flex items-center">
<button onClick={handleCart}>
<GrShop />
</button>
<img
src={userData.photoURL}
alt={userData.displayName}
className="w-9 ml-5 mr-2 rounded-full"
/>
<p className="mr-4">{`${userData && userData.displayName} 님`}</p>
<button onClick={handleGoogleLogOut}>Logout</button>
</div>
)
) : (
<button onClick={handleGoogleLogin}>Login</button>
)}
</div>
);
}
FirebaseConFig
export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
setPersistence(auth, browserSessionPersistence)
.then(() => {
const provider = new GoogleAuthProvider();
return signInWithEmailAndPassword(auth, provider);
})
.catch((error) => {
const errorCode = error.errorCode;
const errorMessage = error.message;
console.log(errorCode, errorMessage);
});
export const db = getFirestore(app);
onAuthStateChanged(auth, (user) => {
if (user != null) {
console.log(user);
console.log("Logged In");
} else {
console.log(user);
console.log("No user");
}
});