I am currently making an API fetching every 3000ms using setInterval method, I noticed the component doesn't re-render with latest data. Below is the code block
const Home = async () => {
let customers = await getCustomers();
setInterval(async () => customers = await getCustomers(), 3000);
}
return (
customers.length > 0 &&
<>
{
customers.map(customer => (<p>{customer.name}</p>)
}
</>
)
Currently the page doesn't update itself unless I manually refresh the page which is bad in UX perspective. Any seniors have any idea on how to make proper polling to backend using server components?
I did trying normal console logging, which it works when I replace the code expression inside setInterval method with console logs. I understand if it's client component it re-render the whole component using useEffect() but since this is the main root component, it has to be the server component by default in Next 13.
Server Components were not designed to maintain a connection with client, therefore, to resolve this issue, you have to convert your Server Component to a Client Component.
In your case, I would maintain that component removing the setInterval and provide make another client component that uses React Query or SWR.
I would pass the initial data to the query method and later revalidating the data with those libraries.
https://tanstack.com/query/v4/docs/react/guides/initial-query-data https://swr.vercel.app/docs/with-nextjs#pre-rendering-with-default-data
There you can find some examples of how to implement the feature with both React Query and SWR.