简体   繁体   中英

Why can't I memoize in NextJS' getServerSideProps?

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
        }
     };
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM