diff --git a/client/src/App.js b/client/src/App.js index 72b22f8..75caa3c 100644 --- a/client/src/App.js +++ b/client/src/App.js @@ -42,6 +42,7 @@ function App() { const fetchUserData = async () => { const token = localStorage.getItem("token"); if (token) { + console.log(token); try { const profileResponse = await axios.get( `${process.env.REACT_APP_API_PATH}/users/profile`, @@ -51,21 +52,21 @@ function App() { }, } ); + setUserData(profileResponse.data); + // Assuming profileResponse.data contains the user object if (profileResponse.data) { - setUserData(profileResponse.data); // Update with actual data dispatch(login()); setIsUserLoggedIn(true); // Set logged in state to true } } catch (error) { console.error("Error fetching user data:", error); - // Handle error appropriately } } }; fetchUserData(); - }, [dispatch, setUserData]); + }, []); return ( diff --git a/client/src/components/UserInformationComponent.js b/client/src/components/UserInformationComponent.js index d33812b..56ae0f3 100644 --- a/client/src/components/UserInformationComponent.js +++ b/client/src/components/UserInformationComponent.js @@ -1,14 +1,44 @@ -import React, { useContext } from "react"; -import { UserContext } from "./UserContext"; +import React, { useEffect, useState, useContext } from "react"; +import { useSelector } from "react-redux"; +import axios from "axios"; import "./css/UserInformationComponent.css"; function UserInformationComponent() { - const { userData } = useContext(UserContext); - console.log(userData); + const [userData, setUserData] = useState({}); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const isLoggedIn = useSelector((state) => state.auth.isLoggedIn); + + useEffect(() => { + const fetchUserData = async () => { + const token = localStorage.getItem("token"); + if (isLoggedIn && token) { + setLoading(true); + try { + const response = await axios.get( + `${process.env.REACT_APP_API_PATH}/users/profile`, + { headers: { Authorization: `Bearer ${token}` } } + ); + setUserData(response.data); + } catch (error) { + console.error("Error fetching user data:", error); + setError("Failed to fetch user data."); + } finally { + setLoading(false); + } + } + }; + + fetchUserData(); + }, [isLoggedIn]); + + if (loading) return
Loading...
; + if (error) return
Error: {error}
; + return (
-

user profile

+

User Profile

{userData.firstName || "First name not set"}