Reputation: 1512
I'm using React + NextJS to display a list of products on a category page.
I can get the products just fine using getServerSideProps
, but I don't like that it re-requests the product list on each visit to the same page. I'm trying to memoize a function that gets the list, and while that seems to work (meaning there are no errors thrown), the supposedly memoized function is still called on subsequent visits to the same page.
See the code below, and note that the "get category" console log is shown in the terminal window when I revisit a page, and in Chrome's network tools I see a fetch request made by NextJS.
How can I make it cache the result of my getCategory
function so it doesn't keep fetching it?
export async function getServerSideProps(context) {
let config = await import("../../config/config");
let getCategory = memoize(async (url) => {
console.log("getting category");
let response = await axios.get(url);
if ( response.status ) {
return response.data;
} else {
return false;
}
});
let response = await getCategory(`${config.default.apiEndpoint}&cAction=getCTGY&ctgyCode=${context.params.code}`);
if ( response ) {
return {
props: {
category: response
}
};
} else {
return {
props: {
category: null
}
};
}
}
Upvotes: 1
Views: 1487
Reputation: 310
getCategory
should be defined outside of getServerSideProps
because as of now, you create a new memoized function for every request
Upvotes: 0
Reputation: 212108
This doesn't work becuase nextjs api routes are "serverless", which means the state that memoize
is supposed to remember is destroyed after HTTP call.
The serverless solution is to use a separate service for caching, which is accessible from your api route.
Otherwise, you may need to look at using a custom server.
Upvotes: 1