I insert data on a mongoDB collection using this endpoint insert.js
import clientPromise from "../../../lib/mongodb";
export default async (req, res) => {
if (req.body["collection"] != null) {
const client = await clientPromise
const db = client.db("myDatabase");
const result = await db.collection("collection").insertOne({
value: parseInt(req.body["collection"]),
createdAt: new Date(),
});
res.status(201).json({time: result});
}
else{
res.status(400).json({});
}
}
This is the the page where I display the last value in the collection index.js
import { useState, useEffect } from "react";
export default function Home() {
const [lastRec, setLastRec] = useState(0)
useEffect(() => { getRecords() }, [])
async function getRecords() {
const res = await fetch('api/record');
const { data } = await res.json();
setLastRec(data[0]["value"])
}
return (
<div className="container">
<div> Last Record = {lastRec} </div>
</div>
)
}
How can I let my react component know when that endpoint was used so it can re-render, whithout the need to click a button, refresh the page or set a timer?