Next.js Discord

Discord Forum

[App-Router] How to correctly memoize requests that depend on another?

Unanswered
Tomistoma posted this in #help-forum
Open in Discord
TomistomaOP
Hello y'all!
I got a memoization issue I don't fully understand. I'm building a Shop-Frontend, and got multiple places where I need the Cart.

So what do I do? I request the cart in the Header component for the Cart-Icon (with item-counter), I fetch it on the footer for a currency-selector, because it holds the information about the currency selected from the user, and I fetch it on the actual cart-page.tsx to display it's content.

I perform these requests like following in on getOrCreateCart()-Method:
const getOrCreateCart = async () => {
  const cart = await getCart() // <- fetches a possible existing cart with a user-id-request-header
  if (!cart) {
    const newCart = await createNewCart()
    return newCart;
  }
  return cart;
}


The fetch-request, that is performed in the getCart()-method got a { next: { revalidate: 0 } } to ensure to always get the non-cached version.

NextJS (v13.5.2) no executes the createNewCart()-method every time when loading the page in all components that execute the getOrCreateCart()-method, and this creates issues on the Backend, because it performs the POST method multiple times, which is absolutely not intended...

What am I missing?

0 Replies