Git Product home page Git Product logo

chatty-pete-course's People

Contributors

tomphill avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

chatty-pete-course's Issues

Props returning undefined

Hi, I have to say I have enjoyed using your video tutorial, well done and easy to understand but I'm stuck I can't get past getServerSideProps used to get values from to be able to load chat after the AI finishes giving the answers. this is my the code, I don't get feedback

/code chatId.js/
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([]);/*to show messages btn user and system */
const [generatingResponse , setGeneratingResponse]=useState(false);
const[fullMessage, setFullMessage] = useState("");
const router = useRouter();

//save newy streamed msg to new chat messages
useEffect(()=>{
if(!generatingResponse && fullMessage){
setNewChatMessages(prev => [...prev,{
_id:uuid(),
role:"assistant",
content:fullMessage,
}])
setFullMessage("");
}
},[generatingResponse, fullMessage])
//when our route changes
useEffect(()=>{
setNewChatMessages([]);
setNewChatId(null)

}, [chatId]);/every time you click new chat empty the above/

/anytime the values change useeffect hook runs/
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("");

//console.log("MESSAGE:",messageText);
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();/read all messages from sendmessg end point/
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 (
<>

<title>New chat</title>


< ChatSidebar chatId={chatId} />


{allMessages.map((message) =>(

) )}
{!! incomingMessage && (

)}



<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"/>
Send





</>
);
}

/*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("ChitChat"); 
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: {}

};
};

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("ChitChat");
const chat = await db.collections("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: { }
}
}*/
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("ChitChat");
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: { }
}
}
/feedback/
props undefined []
[[...chattid]].js:14 props: undefined []

Kindly help

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.