Getting changes on the client with db.collection.watch() and NEXTJS backend api

Viewed 20

For starters, this is a NEXTJS project. Basically, I'm trying to get a response similar to a get response every time a document is added or changed in the MongoDB database. In testing, I get the intended results using the axios get method but in the console, I keep getting some errors that I don't know how to get rid of since my backend knowledge is slim, to say the least. Also when I deploy to Vercel I do not get the intended results.

This is the backend of the code

      if (method === "GET") {
    const taskCollection = Orders;
    const changeStream = taskCollection.watch();
    changeStream.on("change", (change) => {
      return res.status(200).json(change);
    });
  }

And this is the frontend

    useEffect(() => {
    axios.get("/api/Orders2").then((res) => {
      setNewOrder(res.data);
    });
    setRefershOrders(true);
  }, [newOrder]);

The errors: Upon page initialization :

API resolved without sending a response for /api/Orders2, this may result in stalled requests.

Upon changes in the MongoDB document

error - uncaughtException: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

In the local environment, I get the response I want (despite the errors) but in production, I get no response. I know why you cannot set headers after they have already been sent but I honestly didn't mind the error as long as everything worked. Have read some articles that I need to implement sockets but since my backend knowledge is slim I'm having troubles with that as well.

Hope someone can help tnx.

0 Answers
Related