Skip to content
Advertisement

I’m trying to put the data I’m receiving from my API into a table but nothing is displayed

I’m getting data from my API, when I make a console.log or JSON.stringify in the API data it shows without problems but when I pass the data in a table with the map, simply nothing is presented in the table. enter image description here.

const [users, setUsers] = useState([]);
    const loadUser = () => {
        getUsers().then(data => {
            if(data.error) {
                console.log(data.error)
            }else{
              
                setUsers(data)
            }
        })
    }
const inforUsers = () => {
        return(
            <Fragment>
            <table className="table table-bordered mb-5">
                <thead className="thead-dark">
                    <tr>
                        <th scope="col">Id</th>
                        <th scope="col">Nome</th>
                        <th scope="col">Email</th>
                        <th scope="col">role</th>
                        <th scope="col">createdAt</th>
                    </tr>
                </thead>
                <tbody scope="row">
                {Object.keys(users).map((values, key) => (
                    <tr key={key}>
                        <td>
                            {values._id}
                        </td>
                        <td>
                            {values.name}
                        </td>
                        <td>
                            {values.email}
                        </td>
                        <td>
                            {values.role === 1? 'Admin' : 'Simples User'}
                        </td>
                        <td>
                            {values.createdAt}
                        </td>
                    </tr>
                ))} 
                </tbody>
            </table>
            </Fragment>
            )
    }

Advertisement

Answer

I think you are confused about the data you have in hand. The key is the id for each object, so if you want that data, you should access the users object by each of the keys/ids you get from Object.keys. A brief example:

{Object.keys(users).map(id => (
   {users[id]._id}
))}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement