Error props undefined when fetching values from MongoDb

here is my code kindly help me solve this issue

import { getSession } from "@auth0/nextjs-auth0";
import { ChatSidebar } from "components/ChatSidebar/ChatSidebar";
import { Message } from "components/Message";
import clientPromise from "lib/mongodb";
import { ObjectId } from "mongodb";
import Head from "next/head";
import { useRouter } from "next/router";
import { streamReader } from "openai-edge-stream";
import { useEffect, useState } from "react";
import { v4 as uuid } from "uuid";

export default function ChatPage({ chatId, title, messages = [] }) {
    console.log("props: ", title, messages);
    const [newChatId, setNewChatId] = useState(null);
    const [incomingMessage, setIncomingMessage] = useState("");
    const [messageText, setMessageText] = useState("");
    const [newChatMessages, setNewChatMessages] = useState([]);
    const [generatingResponse, setGeneratingResponse] = useState(false);
    const [fullMessage, setFullMessage] = useState("");
    const router = useRouter();

    useEffect(() => {
        if (!generatingResponse && fullMessage) {
            setNewChatMessages((prev) => [
                ...prev,
                {
                    _id: uuid(),
                    role: "assistant",
                    content: fullMessage,
                },
            ]);
            setFullMessage("");
        }
    }, [generatingResponse, fullMessage]);

    useEffect(() => {
        setNewChatMessages([]);
        setNewChatId(null);
    }, [chatId]);

    useEffect(() => {
        if (!generatingResponse && newChatId) {
            setNewChatId(null);
            router.push(`/chat/${newChatId}`);
        }
    }, [newChatId, generatingResponse, router]);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setGeneratingResponse(true);
        setNewChatMessages((prev) => {
            const newChatMessages = [
                ...prev,
                {
                    _id: uuid(),
                    role: "user",
                    content: messageText,
                },
            ];
            return newChatMessages;
        });
        setMessageText("");

        const response = await fetch(`/api/chat/sendMessage`, {
            method: "POST",
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify({ chatId, message: messageText }),
        });

        const data = response.body;
        if (!data) {
            return;
        }

        const reader = data.getReader();
        let content = "";
        await streamReader(reader, (message) => {
            console.log("msg:", message);
            if (message.event === "newChatId") {
                setNewChatId(message.content);
            } else {
                setIncomingMessage((s) => `${s}${message.content}`);
                content = content + message.content;
            }
        });

        setFullMessage(content);
        setIncomingMessage(" ");
        setGeneratingResponse(false);
    };

    const allMessages = [...messages, ...newChatMessages];

    return (
        <>
            <Head>
                <title>New chat</title>
            </Head>
            <div className="grid h-screen grid-cols-[260px_1fr]  ">
                <ChatSidebar chatId={chatId} />
                <div className="flex flex-col overflow-hidden">
                    <div className="flex-1 overflow-auto bg-slate-700 text-white  ">
                        {allMessages.map((message) => (
                            <Message
                                key={message._id}
                                role={message.role}
                                content={message.content}
                            />
                        ))}
                        {!!incomingMessage && (
                            <Message role="assistant" content={incomingMessage} />
                        )}
                    </div>
                    <footer className="bg-slate-800 p-10">
                        <form onSubmit={handleSubmit}>
                            <fieldset className="flex gap-2" disabled={generatingResponse}>
                                <textarea
                                    value={messageText}
                                    onChange={(e) => setMessageText(e.target.value)}
                                    placeholder={generatingResponse ? " " : "ask a question..."}
                                    className="w-full resize-none p-1 rounded-md bg-slate-700 text-white focus:border-emerald-500 focus:bg-slate-600 focus:outline focus:outline-emerald-500"
                                />
                                <button type="submit" className="btn">
                                    Send
                                </button>
                            </fieldset>
                        </form>
                    </footer>
                </div>
            </div>
        </>
    );
}

export const getServerSideProps = async (ctx) => {
    const chatId = ctx.params?.chatId?.[0] || null;
    if (chatId) {
        const { user } = await getSession(ctx.req, ctx.res);
        const client = await clientPromise;
        const db = client.db("Chatty");
        const chat = await db.collection("chats").findOne({
            userId: user.sub,
            _id: new ObjectId(chatId),
        });
        return {
            props: {
                chatId,
                title: chat.title,
                messages: chat.messages.map((message) => ({
                    ...message,
                    _id: uuid(),
                })),
            },
        };
    }
    return {
        props: {
            chatId: null,
            title: null,
        messages[]
      
},
    };
};

I think you have a tipo in the returning :

 return {
        props: {
            chatId: null,
            title: null,
            messages: [], // Corrected line
        },
    };
1 Like

I assume there is more to it than that (I would expect the app to throw an error).


How are you using the component?

As far as I know, getServerSideProps can’t actually send undefined values because it can’t be serialized as JSON. It should throw an error if it did.

Surely messages is an empty array and not undefined, is it not?

If you assign them all default values do you see them in the log?

If you create a test getServerSideProps function and return some fixed values do you see them in the page component?


You probably will have to post a repo with your code.

1 Like

thanks but that doesn’t really affect much, I can’t get values from the database but the fields exist and the connection is perfectly fine. I am using a tutorial

Yes messages is not an empty array and I see the default values in the log

repo code link GitHub - maxallday/chat: Error props undefined when fetching values from MongoDb

1.two identical getServerSideProps functions, which is not allowed. You need to remove one of them.
2. In the second getServerSideProps function, there’s a typo in the db.collections method. It should be db.collection instead of db.collections.
3. There’s a typo in the fieldset tag. The disabled attribute is misspelled as “disabled”.
4. The response.body should be replaced with response.json() to properly handle the response data.
your tipos…

1 Like

I updated the code, i copy pasted and didn’t notice the doubled getserversideprops, i tried changing the json and still dint work

const response = await fetch(`/api/chat/sendMessage`, {
  method: "POST",
  headers: {
    "content-type": 'application/json'
  },
  body: JSON.stringify({ chatId, message: messageText }),
});
const data = await response.json();
if (!data) {
  return;
}

By using await response.json(), you can read the JSON body of the response. This will ensure that data contains the actual response data, allowing you to properly handle the response.
response.body returns a ReadableStream, not the actual data. To extract the data from the response, you need to use methods such as json()

my actual issue is with getserversideprops, when i make the change you are suggesting I dont get response from API

You have to push all the code, we need to see it in context.

What tutorial?

messages default value is an empty array.

If you do not pass anything, or pass undefined, to the parameter it will be an empty array. It entire point of default parameters is to initialize with default values if no value or undefined is passed.

I feed data to the data to the applications and its supposed to display whatever values are in the MongoDB database in my console

What tutorial? the chatgpt tutorial by tomphill udemy course. I cant seem to find out what the problem is

I’ve just uploaded the sendmesssage file

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.