skip to Main Content

Hello fellow StackOverflow community,
I’ve encountred an error when trying to .map() a getDoc() constant in my Next.js app, saying the following: "TypeError: Cannot read properties of undefined (reading ‘map’)". I’m new to Next.js and I would appreciate a lot any kind of help from the community. I’ve been stuck on this error for a very long time trying to search for an answer on internet but nothing.

Here you can review the code of [id].js:

import styled from "styled-components";
import Head from "next/head";
import Sidebar from "../components/Sidebar";
import ChatScreen from "../components/ChatScreen";
import { db } from "../../firebase";
import { collection, doc, orderBy, getDoc } from "firebase/firestore";

const Chat = () => {
  return (
    <Container className="bg-stone-900">
      <Head></Head>
      <Sidebar />
      <ChatContainer>
        <ChatScreen />
      </ChatContainer>
    </Container>
  );
};

export default Chat;

export async function getServerSideProps(context) {
  const ref = doc(collection(db, "chats"), context.query.id);
  const messagesRes = await getDoc(
    ref,
    collection(db, "messages"),
    orderBy("timestamp", "asc")
  );

  const messages = messagesRes.docs
    .map((doc) => ({ //Here is the error line.
      id: doc.id,
      ...doc.data(),
    }))
    .map((messages) => ({
      ...messages,
      timestamp: messages.timestamp.toDate().getTime(),
    }));

  const chatRes = await getDoc();
  const chat = {
    id: chatRes.id,
    ...chatRes.data(),
  };

  return {
    props: {
      messages: JSON.stringify(messages),
      chat: chat,
    },
  };
}

const Container = styled.div`
  margin: 0 auto;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const ChatContainer = styled.div`
  margin: 0 auto;
  overflow: scrollbar;
`;

Again, thanks for any answers!

2

Answers


  1. This issue is a nightmare for a lot of us starting out. I know I struggled with it as well. That said, the datasnapshot returns a json object. The .map() function is for arrays. Therefore it has to be manipulated so the map knows how to iterate through it.

    Per w3

    array.map(function(currentValue, index, arr), thisValue). 
    

    So your

    data.map(Object.entries(JSON.parse(data)));
    
    Login or Signup to reply.
  2. It should be getDocs if you are trying to loop through the docs array,you cannot loop through using getDoc since it only returns a single document which is not an array, hence why you are getting undefined.

    You can try the code below to loop through the messages using getDocs

    const ref = doc(collection(db, "chats"), context.query.id);
      const messagesRes = await getDocs(
        ref,
        collection(db, "messages"),
        orderBy("timestamp", "asc")
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search