Home > Net >  how to print dynamic data in React component?
how to print dynamic data in React component?

Time:09-22

so the problem is I´m trying to print data according to the length of an array. This is the solution I´ve tried. Of course it doesn´t work. I don´t completely know why but I´m sure it´s because the cb function in the forEach is not being processed as I want. Here´s the code:

function Users(props){
    const [users, setUsers] = useState([user]);

    useEffect(() => {
        fetch('http://127.0.0.1:8000/api/users').then((res) =>{
            
            return res.json();
        }).then(res => {

            setUsers(res);
        });
    }, []);

    return (
            <div>
                {users.forEach((user) =>{
                    return(
                    <ul>
                        <li>{user.firstName}</li>
                        <li>{user.lastName}</li>
                        <li>{user.avatar}</li>
                    </ul>);})}
            </div>
        );
}

CodePudding user response:

try this

function Users(props){
    const [users, setUsers] = useState([user]);

    useEffect(() => {
        fetch('http://127.0.0.1:8000/api/users').then((res) =>{
            
            return res.json();
        }).then(res => {

            setUsers(res);
        });
    }, []);

    return (
            <div>
                {users.map((user) =>{
                    return(
                    <ul>
                        <li>{user.firstName}</li>
                        <li>{user.lastName}</li>
                        <li>{user.avatar}</li>
                    </ul>);})}
            </div>
        );
}

CodePudding user response:

You can do as SwaD said or like this if you have nothing else to do except render your data :

`function Users(props){ const [users, setUsers] = useState([user]);

useEffect(() => {
    fetch('http://127.0.0.1:8000/api/users')
    .then( res => res.json() )
    .then(res => {
        setUsers(res);
    });
}, []);

return (
        <div>
            {users.map((user) => (
                <ul>
                    <li>{user.firstName}</li>
                    <li>{user.lastName}</li>
                    <li>{user.avatar}</li>
                </ul>)
            )}
        </div>
    );

}`

  • Related