Get MongoDB Stream Real Time data in the front facing

I am trying to get the my MongoDB Atlas changes updated in real time in the front user facing. I am trying to implement the Mongo Change Stream functions. I am able to get the changes in my file but not sure how I will pass those changes to the front-end page.
Inside my Mongodb Stream file I am already getting the changes from MongoDB, all changes are being showing on that “change” inside the “for while”. I just need to know how I can pass that to the front facing part. If someone could help me on that, I tried some stuff but nothing worked there.

I am working with 3 files –

The Main front facing file code –

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>'use client';
import { useEffect, useState, useCallback } from 'react';
import axios from 'axios';
import { columns } from './columns';
import { DataTable } from './DataTable';
export default function JobsTable() {
const [sseConnection, setSSEConnection] = useState(null);
const [jobs, setJobs] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await axios.get('/api/jobs');
setJobs(response.data);
};
fetchData();
}, []);
const listenToSSEUpdates = useCallback(() => {
console.log('listenToSSEUpdates func');
const eventSource = new EventSource('/api/sse');
}, []);
useEffect(() => {
listenToSSEUpdates();
return () => {
if (sseConnection) {
sseConnection.close();
}
};
}, [listenToSSEUpdates]);
return (
<div>
{' '}
<DataTable columns={columns} data={jobs} />{' '}
</div>
);
}
</code>
<code>'use client'; import { useEffect, useState, useCallback } from 'react'; import axios from 'axios'; import { columns } from './columns'; import { DataTable } from './DataTable'; export default function JobsTable() { const [sseConnection, setSSEConnection] = useState(null); const [jobs, setJobs] = useState([]); useEffect(() => { const fetchData = async () => { const response = await axios.get('/api/jobs'); setJobs(response.data); }; fetchData(); }, []); const listenToSSEUpdates = useCallback(() => { console.log('listenToSSEUpdates func'); const eventSource = new EventSource('/api/sse'); }, []); useEffect(() => { listenToSSEUpdates(); return () => { if (sseConnection) { sseConnection.close(); } }; }, [listenToSSEUpdates]); return ( <div> {' '} <DataTable columns={columns} data={jobs} />{' '} </div> ); } </code>
'use client';

import { useEffect, useState, useCallback } from 'react';
import axios from 'axios';

import { columns } from './columns';
import { DataTable } from './DataTable';

export default function JobsTable() {
  const [sseConnection, setSSEConnection] = useState(null);
  const [jobs, setJobs] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get('/api/jobs');
      setJobs(response.data);
    };

    fetchData();
  }, []);

  const listenToSSEUpdates = useCallback(() => {
    console.log('listenToSSEUpdates func');
    const eventSource = new EventSource('/api/sse');
  }, []);

  useEffect(() => {
    listenToSSEUpdates();

    return () => {
      if (sseConnection) {
        sseConnection.close();
      }
    };
  }, [listenToSSEUpdates]);

  return (
    <div>
      {' '}
      <DataTable columns={columns} data={jobs} />{' '}
    </div>
  );
}

My API SSE File:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { changeStream } from '@/lib/mongoChangeStream';
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
const HEARTBEAT_INTERVAL = 5000; // 5 seconds (adjust this as needed)
export async function GET(req, res) {
// Check if the client accepts SSE
const headersList = headers();
const accept = headersList.get('accept');
return new NextResponse('ok');
}
</code>
<code>import { changeStream } from '@/lib/mongoChangeStream'; import { NextResponse } from 'next/server'; import { headers } from 'next/headers'; const HEARTBEAT_INTERVAL = 5000; // 5 seconds (adjust this as needed) export async function GET(req, res) { // Check if the client accepts SSE const headersList = headers(); const accept = headersList.get('accept'); return new NextResponse('ok'); } </code>
import { changeStream } from '@/lib/mongoChangeStream';
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';


const HEARTBEAT_INTERVAL = 5000; // 5 seconds (adjust this as needed)


export async function GET(req, res) {
  // Check if the client accepts SSE
  const headersList = headers();
  const accept = headersList.get('accept');


  return new NextResponse('ok');
}

My MongoDB Stream Connection:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { MongoClient } from 'mongodb';
const uri = process.env.DATABASE_URL || '';
const client = new MongoClient(uri);
export let changeStream;
async function run() {
try {
console.log('Setting up change stream');
const database = client.db('pcb');
const collection = database.collection('Jobs');
const options = { fullDocument: 'updateLookup' };
// This could be any pipeline.
const pipeline = [];
// Open a Change Stream on the "jobs" collection
changeStream = collection.watch(pipeline, options);
// Print change events as they occur
for await (const change of changeStream) {
console.log('Received change:n', change);
}
// Close the change stream when done
await changeStream.close();
} finally {
// Close the MongoDB client connection
await client.close();
}
}
run().catch(console.dir);
</code>
<code>import { MongoClient } from 'mongodb'; const uri = process.env.DATABASE_URL || ''; const client = new MongoClient(uri); export let changeStream; async function run() { try { console.log('Setting up change stream'); const database = client.db('pcb'); const collection = database.collection('Jobs'); const options = { fullDocument: 'updateLookup' }; // This could be any pipeline. const pipeline = []; // Open a Change Stream on the "jobs" collection changeStream = collection.watch(pipeline, options); // Print change events as they occur for await (const change of changeStream) { console.log('Received change:n', change); } // Close the change stream when done await changeStream.close(); } finally { // Close the MongoDB client connection await client.close(); } } run().catch(console.dir); </code>
import { MongoClient } from 'mongodb';


const uri = process.env.DATABASE_URL || '';
const client = new MongoClient(uri);


export let changeStream;


async function run() {
  try {
    console.log('Setting up change stream');
    const database = client.db('pcb');
    const collection = database.collection('Jobs');


    const options = { fullDocument: 'updateLookup' };
    // This could be any pipeline.
    const pipeline = [];


    // Open a Change Stream on the "jobs" collection
    changeStream = collection.watch(pipeline, options);


    // Print change events as they occur


    for await (const change of changeStream) {
      console.log('Received change:n', change);
    }


    // Close the change stream when done
    await changeStream.close();
  } finally {
    // Close the MongoDB client connection


    await client.close();
  }
}


run().catch(console.dir);

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật