'use server';
import { RawMenuData } from '@/app/api/types/RawMenuData';
import { processMenuData } from '@/utils/dataProcessingLogic/processMenuData';
import { ProcessedMenuData } from '@/app/api/types/ProcessedMenuData';
import { unstable_cache } from 'next/cache';
import { CONTENT_TYPE_HEADER, AUTHORIZATION_HEADER } from '@/constants/HTTP_HEADERS';
const { CMS_ORGANIZATION_ID, CMS_API_URL, CMS_API_TOKEN } = process.env;
interface Result {
menuData?: ProcessedMenuData;
errorMessage?: string;
}
export const getMenuData = unstable_cache(
async (): Promise<Result> => {
const apiToken = CMS_API_TOKEN ;
const getRawMenuDataResponse = await fetch(`${CMS_API_URL}/api/1/nomenclature`, {
headers: { ...CONTENT_TYPE_HEADER, ...AUTHORIZATION_HEADER(apiToken) },
method: 'POST',
body: JSON.stringify({
organizationId: CMS_ORGANIZATION_ID,
}),
cache: 'force-cache',
next: { tags: ['menu'] },
});
if (!getRawMenuDataResponse.ok) {
throw new Error(
`HTTP error`
);
}
const getRawMenuDataResponseData: RawMenuData = await getRawMenuDataResponse.json();
const proceccedMenuData = processMenuData(getRawMenuDataResponseData);
console.log(`[SERVER ACTION - getMenuData] - Success`);
return { menuData: proceccedMenuData };
} catch (error) {
console.log(`ERROR: [SERVER ACTION - getMenuData]`);
return { errorMessage: 'Error' };
}
},
['menu'],
{
tags: ['menu'],
}
);
In my app I have 7 pages and each page uses getMenuData like this: const { menuData } = await getMenuData()
However even tho I use unstable_cache - when I build my app I see that getMenuData is being called 7 times instead of just one. The requests to the CMS are not duplicated because of fetch caching but still im worrying - is it fine that getMenuData is being called multiple times? Is it fine or there is a better approach?