I'm using NextJS 14.0.3 with MongoDB Change Streams and need to update a client component when a change is detected in the database. When I change something on my database, it detects the change, but doesn't update the component. I assume it's because I'm not using useState, but that's not support on server components.
This is what I have on my page.tsx
import Logs from "./components/Logs";
import GetLogs from "@/actions/GetLogs";
import Log from "@/models/log.model";
import { connectDatabase } from "@/lib/db";
import LogTable from "./components/LogTable";
connectDatabase();
export default async function Logs() {
let logs: any[] = await GetLogs();
Log.watch().on("change", (change: any) => {
switch (change.operationType) {
case "insert":
logs = [change.fullDocument, ...logs];
break;
case "update":
logs = logs((log) =>
log._id === change.documentKey._id
? change.fullDocument
: log
);
break;
case "delete":
logs = logs.filter(
(log) => log._id !== change.documentKey._id
);
break;
default:
break;
}
});
return (
<section className="flex flex-col gap-4 w-full">
<LogTable logs={logs} />
</section>
);
}
I tried using a client component with a useState and passed it into a server component, but Nextjs doesn't like that.