Dispatching Storefront Actions from a custom component
Key Takeaway
Import the factory method for the operation from commerce/actionApi, then create the Action with the input that method expects. For example, removing an item from a cart takes the cart item's ID, not the product's ID.
A Storefront Action is an event, such as adding an item to a cart or using a filter to search on a product variant, that a custom Lightning Web Component (LWC) can dispatch in a B2B store built with an LWR template. The closest applicable Data Provider carries out the operation, so related components like the cart refresh without your component managing that chain itself. Your main job is to pick the right factory method and give it the input it expects.
Where Storefront Actions fit
Storefront APIs come in three kinds, and all three are supported in B2B stores built with LWR templates. Each kind differs in how and when it retrieves data for your component.
- Imperative APIs are process-oriented functions that call a Connect API method (POST, PUT, PATCH) and return an outcome as a Promise. One example is
addItemToCart(productId, quantity)incommerce/cartApi. - Wire Adapters call a GET method and automatically update the component's properties when the hosted source data changes.
- Storefront Actions are events that trigger updates to closely related LWCs. Unlike direct communication with a backend API endpoint, they react to UI clicks more responsively by changing related page-level components in a chain, within a nearby (proximate) scope.
A Storefront Action is not a direct backend call, but it can still result in calls to REST API endpoints through Wire Adapters or Imperative APIs. So don't assume an Action never reaches the server.
A State Management layer coordinates operations that update builder components on the page. For example, when a buyer adds a product to the cart through a Storefront API, State Management makes sure the list of cart items and the cart status icon update too.
Components built on Storefront APIs have advantages over components that rely on platform UI APIs and Aura controllers.
- Storefront APIs automatically apply guardrails such as buyer entitlement.
- Storefront APIs avoid requesting the same data more than once by using browser, CDN and server cache layers.
- Storefront APIs keep the customer experience consistent across related components.