/** * Write a component that will get a user by {{userId}} and display basic data * Use fetchUser for the request */ export const User: FC<Props> = ({ userId }) => { // Write your solution here: const user = userId && fetchUser({ id: userId }); if (!user) return null; return ( <div className="stack column"> <div>UserId: </div> <div>UserName: </div> </div> ); };
sobes.tech AI
Answer from AI
tsx import React, { FC, useEffect, useState } from 'react';
interface Props { userId: string; }
interface User { id: string; name: string; // other fields as needed }
// Assumes fetchUser returns a Promise<User>
async function fetchUser(params: { id: string }): Promise<User> {
// Implementation of API request
const response = await fetch(/api/users/${params.id});
if (!response.ok) throw new Error('Failed to fetch user');
return response.json();
}
export const User: FC<Props> = ({ userId }) => { const [user, setUser] = useState<User | null>(null); const [loading, setLoading] = useState<boolean>(false); const [error, setError] = useState<string | null>(null);
useEffect(() => { if (!userId) { setUser(null); return; } setLoading(true); setError(null); fetchUser({ id: userId }) .then(setUser) .catch(() => setError('Error loading user')) .finally(() => setLoading(false)); }, [userId]);
if (loading) return <div>Loading...</div>; if (error) return <div>{error}</div>; if (!user) return null;
return ( <div className="stack column"> <div>UserId: {user.id}</div> <div>UserName: {user.name}</div> </div> ); };