How to fix Error: Objects are not valid as a React child (found: [object Promise])

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    in ul (at ChatRoom.js:16)

It throws this error for some reason. Here’s my code:

const [messages] = useCollectionData(query, { idField: 'id' });
return (
    <div className={classes.ChatRoomContainer}>
        <ul>
            {messages ? messages && messages.map(async msg => {
                const messageClass = msg.userId === props.userId ? classes.Sent : classes.Recieved;
                let username;
                await firebase.firestore().collection('users').doc(msg.author).get().then(doc => {
                    username = doc.data().userName;
                });
                return <li className={messageClass + ' ' + classes.Message} key={msg.id}>
                    <label>{msg.author !== props.userId ? username : 'You'}</label>
                    <p className={classes.MessageContent}>{msg.messageContent}</p>
                </li>
            }) : <p>Loading...</p>}
        </ul>
        <form className={classes.Form} onSubmit={(e) => props.onMessageSentHandler(e)}>
            <input className={classes.Input} placeholder="Type your message..." onChange={(e) => props.onInputChangedHandler(e)} value={props.messageInput} />
            <button className={classes.Btn}><FontAwesomeIcon color="white" icon='paper-plane' className={classes.PaperPlaneIcon} /></button>
        </form>
    </div>
)

Is there some way to fix it? It only appears if I use async by the way.

Answer

You’re trying to execute the Promise twice.

async/await and .then().catch are two different syntaxes.

Try this:

let doc = await firebase.firestore().collection('users').doc(msg.author).get();

and then read the username from it:

return (
    <li className={messageClass + ' ' + classes.Message} key={msg.id}>
       <label>{msg.author !== props.userId ? doc.data().username : 'You'}</label>
       <p className={classes.MessageContent}>{msg.messageContent}</p>
    </li>
)