-1

When I try to log the whole MongoDb table, it logs everything in it. However, when I try to log user.createdAt separately, it logs undefined. When i use user.createdAt.toString() it shows an error (toString for undefined)

When using Date(user.createdAt), it works fine but the new problem is I have 6 user details. Only 1 of them has createdAt field and its value date. But it logs 6 times and the same date for 6 users, but the other user doesn't even have the createdAt field. I am using nextjs project and array map to render it in a table of users

const users = await fetchUsers();

console.log(users);


{users.map(user => (

    <tr key={user.id}>

        <td>

            <div className={styles.user}>

                <Image src={user.img || "/noavatar.png"} alt="userAvatar" width={40} height={40} className={styles.userImage} />

                {user.username}

            </div>

        </td>

        <td>{user.email}</td>

        <td>{user.createdAt?.toString().slice(4,16)}</td>

        <td>{user.isAdmin ? "Admin" : "Client"}</td>

        <td>{user.isActive ? "Active" : "Passive"}</td>

        <td>

            <div className={styles.buttons}>

                <Link href={`/dashboard/users/${user.id}`}>

                    <button className={`${styles.button} ${styles.view}`} >VIEW</button>

                </Link>

                <Link href="/">

                    <button className={`${styles.button} ${styles.delete}`} >DELETE</button>

                </Link>

            </div>

        </td>

    </tr>

))}

I tried logging with conditions but it like somekind of undefined data

1 Answer 1

0

try using this code:

{users.map(user => {

return (

<tr key={user.id}>

    <td>

        <div className={styles.user}>

            <Image src={user.img || "/noavatar.png"} alt="userAvatar" width={40} height={40} className={styles.userImage} />

            {user.username}

        </div>

    </td>

    <td>{user.email}</td>

    <td>{user.createdAt?.toString().slice(4,16)}</td>

    <td>{user.isAdmin ? "Admin" : "Client"}</td>

    <td>{user.isActive ? "Active" : "Passive"}</td>

    <td>

        <div className={styles.buttons}>

            <Link href={`/dashboard/users/${user.id}`}>

                <button className={`${styles.button} ${styles.view}`} >VIEW</button>

            </Link>

            <Link href="/">

                <button className={`${styles.button} ${styles.delete}`} >DELETE</button>

            </Link>

        </div>

    </td>

</tr>

)})

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.