Next.js Discord

Discord Forum

Is this is best solution??

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
Hi, guys.
A little help is appreciated
I want to know if this is the best approach or not
I was thinking of using noStore with unstable_cahe() with a tag
I don't want to cache data but want to have a tag for it but if I use cache I cant pass revalidate to 0 and unstabe_noStore() with cache() dont work
import { unstable_noStore, unstable_cache as cache, revalidateTag } from 'next/cache';

type Params = {
  page: number;
  limit: number;
  search?: string;
};

export const getEntities = async (
  params: Params
): Promise<EntityResponse|any> => {
  'use server';
  unstable_noStore();

  const fetchEntities = async (params: Params) => {
    const page = Number(params.page) || 1;
    const pageLimit = Number(params.limit) || 10;
    const name = params.search || null;
    const offset = (page - 1) * pageLimit;

    const whereClause = name ? { name: { contains: name } } : {};

    const [entities, totalEntities] = await Promise.all([
      prisma.entity.findMany({
        skip: offset,
        take: pageLimit,
        where: whereClause
      }),
      prisma.entity.count({
        where: whereClause
      })
    ]);

    const pageCount = Math.ceil(totalEntities / pageLimit);
    const metadata = {
      total: totalEntities,
      pageCount,
      currentPage: page,
      perPage: pageLimit
    };

    return { entities, metadata };
  };

  return await cache(
    async () => {
      try {
        const { entities, metadata } = await fetchEntities(params);
        return { data: entities, metadata };
      } catch (error) {
        console.error('Server errors:', error.message);
        return { data: [], metadata: {} };
      }
    },
    [`entities`, JSON.stringify(params)],
    {
      revalidate: 1,
      tags: [`entities`, JSON.stringify(params)]
    }
  )();
};

0 Replies