skip to Main Content

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


  1. Chosen as BEST ANSWER

    i had this const [messages, setMessages] = useState(""); and if i change that to const [messages, setMessages] = useState([]); it works


  2. You 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:

    const [isLoading, set_isLoading] = true;
    
    getFirebaseData().then(() => set_isLoading(false))
    
    if(isLoading) return "Loading...";
    
    return <div>{messages.map( ... )}</div>
    

    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 of messages.map.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search