To display the username after separating frontend and backend, follow these steps:
-
Store Username in State: Use React’s useState to manage the username state on the frontend.
-
Fetch Username from Backend:
- Create an API endpoint (e.g., /api/users/me) that returns the logged-in user’s data.
-
Use Axios or fetch to call this endpoint in a function, updating the state with the received username.
-
Handle Loading and Errors:
- Implement loading states using useState to disable buttons or show spinners while fetching.
-
Add error handling to catch issues and display messages to the user.
-
Display Username: Use the stored username in components, such as showing a welcome message.
Example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import axios from ‘axios’; import { useState } from ‘react’; function Header() { const [username, setUsername] = useState(”); const [loading, setLoading] = useState(true); const [error, setError] = useState(”); async function fetchUsername() { try { const response = await axios.get(‘/api/users/me’); setUsername(response.data.username); } catch (err) { setError(‘Failed to fetch username. Please try again.’); } finally { setLoading(false); } } if (loading) return <div>Loading...</div>; return ( <header> {error && <p className=“error”>{error}</p>} <h1>Welcome back, {username}!</h1> </header> ); } |
This approach separates concerns and ensures the frontend only displays data fetched from the backend.
Leave a Reply
You must be logged in to post a comment.