I follow this official mongodb [tutorial]. (Real Time Data in a React JavaScript Front-End with Change Streams | MongoDB). Code below:
import React, { useState, useEffect } from "react"
import * as Realm from "realm-web";
// Create the Application
const app = new Realm.App({ id: "application-0-wfjzk" });
// Define the App component
const App = () => {
// Set state variables
const [user, setUser] = useState();
const [events, setEvents] = useState([]);
// This useEffect hook will run only once when the page is loaded
useEffect(() => {
const login = async () => {
// Authenticate anonymously
const user = await app.logIn(Realm.Credentials.anonymous());
setUser(user);
// Connect to the database
const mongodb = app.currentUser.mongoClient("mongodb-atlas");
const collection = mongodb.db("data").collection("changestream");
// Everytime a change happens in the stream, add it to the list of events
for await (const change of collection.watch()) {
setEvents(events => [...events, change]);
}
}
login();
}, []);
// Return the JSX that will generate HTML for the page
return (
<div className="App">
{!!user &&
<div className="App-header">
<h1>Connected as user ${user.id}</h1>
<div>
<p>Latest events:</p>
<table>
<thead>
<tr><td>Operation</td><td>Document Key</td><td>Full Document</td></tr>
</thead>
<tbody>
{events.map((e, i) => (
<tr key={i}><td>{e.operationType}</td><td>{e.documentKey._id.toString()}</td><td>{JSON.stringify(e.fullDocument)}</td></tr>
))}
</tbody>
</table>
</div>
</div>
}
</div>
);
};
export default App;
It’s working and If i tried to add data from atlas database it will reflect in the browser but after few seconds it shows the error below in console:
bundle.dom.es.js:1692 Uncaught (in promise) WatchError: rule with id=“638f205a679de70c4589d429” no longer exists on mongodb service, closing watch stream
at WatchStream.feedSse (bundle.dom.es.js:1692:1)
at WatchStream.feedLine (bundle.dom.es.js:1617:1)
at WatchStream.advanceBufferState (bundle.dom.es.js:1752:1)
at WatchStream.feedBuffer (bundle.dom.es.js:1596:1)
at MongoDBCollection.watchImpl (bundle.dom.es.js:1945:1)
at async login (App.js:28:1)
After that, I can’t see the changes happening in the browser even if I add data.