To fetch data on the server side and update it every minute while the user is on the page, you can use a combination of Incremental Static Regeneration (ISR) and client-side updates. Here's how you can achieve this:
- Use ISR to revalidate the page every minute on the server:
export const revalidate = 60;
export default async function Home() {
const data = await getLatestPrices();
return <div>{data}</div>;
}
This approach uses the revalidate option to regenerate the page every 60 seconds (1 minute) on the server Next.js Docs: ISR (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#time-based-revalidation).
- To update the data on the client side while the user is on the page, you can use a client-side component with a
useEffect hook and setInterval to fetch new data every minute.
Here's an example of how you can combine these approaches:
import { Suspense } from 'react';
import LatestPrices from './LatestPrices';
export const revalidate = 60;
export default async function Home() {
const initialData = await getLatestPrices();
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LatestPrices initialData={initialData} />
</Suspense>
</div>
);
}
'use client';
import { useState, useEffect } from 'react';
export default function LatestPrices({ initialData }) {
const [data, setData] = useState(initialData);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('/api/latest-prices');
const newData = await response.json();
setData(newData);
};
const interval = setInterval(fetchData, 60000);