Next.js 14 (App router) shows the old data

325 Views Asked by At

Colleagues I need help. I'm working on a project using Next.js 14.0.3. There is an API that I access to get data. This data is news articles that are updated/added through the admin panel. The problem is that Next caches data by default, and when I first open the site, I receive old data from the cache, and not updated data.

How can I make Next compare new data with data from the cache? If the new data differs from the cached data, then it should give me new data. In this case, if the data has not yet changed, requests should not be sent to the server. I tried using cache: “no-store” and revalidate: 30, but it didn't work. Hope you can help me.

Here is my code I provided below:

export const apiUrl = process.env.API_URL;
export async function getNews(
  lng: string,
  catId: string,
  page: string,
  perPage: string
) {
  const res = await fetch(
    `${apiUrl}/blogs/index?hl=${lng}&cat_id=${catId}&page=${page}&per_page=${perPage}`,
    { next: { revalidate: 30 } }
  );
  if (!res.ok) throw new Error('Failed to fetch the news');
  return res.json();
}

import { NewsItem } from '@/components';
import { getNews } from '@/api';
import { NewsModel, SearchParamsType } from '@/api/types';
import { getCurrentLocale, getI18n } from '@/locales/server';

export default async function NewsPage({
  searchParams,
}: {
  searchParams: SearchParamsType;
}) {
  const locale = getCurrentLocale();
  const tDay = await getI18n();
  const page = searchParams['page'] ?? '0';
  const per_page = searchParams['per_page'] ?? '20';
  if (!searchParams.blogs_cat_id) searchParams.blogs_cat_id = '282';
  const data: { models: NewsModel[] } = await getNews(
    locale,
    searchParams.blogs_cat_id,
    page,
    per_page
  );

  return <NewsItem data={data} locale={locale} tDay={tDay} />;
}
0

There are 0 best solutions below