Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
        );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading