woocommerce / woocommerce

A customizable, open-source ecommerce platform built on WordPress. Build any commerce solution you can imagine.
https://woocommerce.com
9.32k stars 10.74k forks source link

Mini Cart always trigger a request to Store API's Cart even if its' empty #50793

Open senadir opened 3 weeks ago

senadir commented 3 weeks ago

On a default, new guest session, Mini Cart will always trigger request to store/cart, even if the session is new and has nothing, this happens on multiple refreshes and cache in local storage doesn't matter.

Steps to reproduce

  1. On a guest session, go to a page with mini cart.
  2. Notice a request to store/cart in network.
  3. Remove Mini Cart.
  4. Notice that the request is now gone.

I tried with a combo of settings for mini cart and they all produced the request regardless.

Expected Behavior

There should be no request on page load, on each page, for guest sessions at least.

Current behavior

A request is always made.

clifgriffin commented 3 weeks ago

Following up here from the Slack discussion:

I think this needs to be solved in the cart redux store, not in individual blocks. For example, the product button block has the same issue.

That way any block that calls getCartData(), etc can do so with peace of mind that it will get the correct data, even if that data is defaulted because the session is new, or pulled from local storage cache if not new and the cart hasn't changed between requests.

This latter caching concern will be very important for high traffic WooCommerce installs. Right now, 10k requests to a site will generate 10k non-cacheable server requests.

mikejolley commented 2 weeks ago

Mini Cart also does its own additional request via getMiniCartTotalsFromServer, so there are 2 API calls on page load. This should be consolidated.

mikejolley commented 2 weeks ago

Since this has high priority I will summarise what I've found so far.

On page load mini cart pulls what it thinks if the latest data from localStorage and also does a request to get the latest values from the server

https://github.com/woocommerce/woocommerce/blob/d9a47a15a97d386759bb46519b156a789a0ffcde/plugins/woocommerce-blocks/assets/js/blocks/mini-cart/frontend.ts#L27-L28

This was added in this PR to support static page caching, which generally affects logged out/guest customers. When static page caching is present, we cannot hydrate from the server on the page.

p1724856756078859-slack-C8X6Q7XQU

On regular pages, there is 1 request to the API via getMiniCartTotalsFromServer

On the shop page, there is the getMiniCartTotalsFromServer request plus a duplicate request via the getCart call from product buttons: https://github.com/woocommerce/woocommerce/blob/d9a47a15a97d386759bb46519b156a789a0ffcde/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/frontend.tsx#L219-L227

I will move this into next cycle for consideration.