when add this code, the app runs as suposed to, but when i reload the app, it stops rendering as it should and give me a full blanck page
</div>
<div className="chat__body">
{messages.map((message) => (
<p className={`chat__message ${true && "chat__reciever"}`}>
<span className="chat__name">{message.name}</span>
{message.message}
<span className="chat__timestamp">
{new Date(message.timestamp?.toDate()).toUTCString()}
</span>
</p>
))}
</div>
whith this message error when inspecting Uncaught TypeError: messages.map is not a function
do someone know what am i doing wrong?
2
Answers
i had this
const [messages, setMessages] = useState("");
and if i change that toconst [messages, setMessages] = useState([]);
it worksYou haven’t provided enough code but I’m guessing you’re probably not accounting for the loading time of your Firebase data.
messages.map
is the culprit, you’re trying to loop over messages but they’re initially empty until Firebase has a chance to send you back the data.You would need to check if the data is loaded before accessing it. A quick example in pseudo-code would be:
But I would recommend using a firebase library that can provide this type of functionality for you.
Another workaround is also to use optional chaining to have safer code:
messages?.map
instead ofmessages.map
.