skip to Main Content

I’m building a React application where I have a ViewUser component responsible for displaying user details fetched from an API using Axios. However, I’m facing an issue where the user details are not displaying as expected in the component. I’ve tried various troubleshooting steps, including initializing the state with empty strings, but the issue persists.

[[enter image description here](https://phpout.com/wp-content/uploads/2023/09/lwppT.png)](https://phpout.com/wp-content/uploads/2023/09/s4dKV.png)

can anyone help me with this?

‘ve confirmed that the API endpoint returns the expected data, and the id parameter is correctly extracted from the URL. However, the user details do not display in the component.

import axios from 'axios';
import React, { useState, useEffect } from 'react'
import { Link, useParams } from 'react-router-dom'

export default function ViewUser() {

    const [user, setUser] = useState({
        name: "",
        username: "",
        email: ""
    });
    
    

    const { id } = useParams();
    

    useEffect(() => {
        loadUser();
    }, []);

    const loadUser = async () => {
        try {
            const result = await axios.get(`http://localhost:8080/user/${id}`);
            console.log(result.data); // Log the fetched user data
            setUser(result.data);
        } catch (error) {
            console.error("Error loading user:", error);
        }
    };
    

    

    return (
        <div className='container'>
            <div className='row'>
                <div className='col-md-6 offset-md-3 border rounded p-4 mt-2 shadow'>
                    <h2 className='text-center m-4'> User Details</h2>
                    <div className='card'>
                        <div className='card-header'>
                            Details of User id : {user.id}
                            <ul className='list-group list-group-flush'>
                                <li className='list-group-item'>
                                    <b>Name:</b>
                                    {user.name}
                                </li>
                                <li className='list-group-item'>
                                    <b>Username:</b>
                                    {user.username}
                                </li>
                                <li className='list-group-item'>
                                    <b>Email:</b>
                                    {user.email}
                                </li>
                            </ul>
                        </div>

                    </div>
                    <Link className="btn btn-primary my-2" to="/">Back to Home</Link>
                </div>
            </div>
        </div>
    )
}

Can someone please help me identify what might be causing this issue or suggest additional troubleshooting steps to resolve it? Any insights or guidance would be greatly appreciated.

2

Answers


  1. Change useEffect to

    useEffect(() => {
        loadUser();
    }, [id]);
    
    Login or Signup to reply.
  2. It doesn’t look like there’s anything enforcing your state change getting noticed, or your code snippet is incomplete. Usually (or rather, in my experience), a feature like this involves some kind of loading indicator and some other coding infrastructure to be aware of the loading state and render the corresponding components appropriately. Something like (psuedocode):

    loadUser = async () => {
        setLoading(true)
        await axios.get(`http://localhost:8080/user/${id}`)
            .then((data) => {
                setUser(data)
            })
            .catch((error) => { 
                console.error("Error loading user:", error);
            })
            .finally(() => {
                setLoading(false)
            })
    })
    

    Then you return {loading, data} from viewUser and gatekeep rendering your component with something like {!loading && user ? <UserView user={user} /> : <LoadingSpinner />}

    As a thing to watch for: Notice that you’re not actually awaiting the result of loadUser in your useEffect. You shouldn’t be, but seeing that the promise resolution is ignored (not awaited) should be a clue that there’s more to be done in the architecture of your solution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search