React Function Component

Created by admin@example.com on March 28, 2025

1
import React, { useState, useEffect } from 'react';
2
3
const UserProfile = ({ userId }) => {
4
  const [user, setUser] = useState(null);
5
  const [loading, setLoading] = useState(true);
6
  
7
  useEffect(() => {
8
    const fetchUser = async () => {
9
      try {
10
        const response = await fetch(`/api/users/${userId}`);
11
        const data = await response.json();
12
        setUser(data);
13
      } catch (error) {
14
        console.error('Failed to fetch user:', error);
15
      } finally {
16
        setLoading(false);
17
      }
18
    };
19
    
20
    fetchUser();
21
  }, [userId]);
22
  
23
  if (loading) return <div>Loading...</div>;
24
  if (!user) return <div>User not found</div>;
25
  
26
  return (
27
    <div className="user-profile">
28
      <h2>{user.name}</h2>
29
      <p>Email: {user.email}</p>
30
      <p>Joined: {new Date(user.createdAt).toLocaleDateString()}</p>
31
    </div>
32
  );
33
};
34
35
export default UserProfile;