Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Render react component whenever API endpoint is consumed NextJS

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!