how to print dynamic data in React component?

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>
        );
}

>Solution :

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>
        );
}

Leave a Reply