• websites

Shopping Cart

We use amp-list, to show a dynamic list of items in the cart.

amp-list needs to send the session cookie on the header of the request, so that the server can retrieve the contents of the cart on the session. For this reason, we use credentails="include", as an additional attribute.

Each row of this list, contains a button to remove items from the cart, that works in the following way:

  1. Clicking on the "remove" button, updates an state object (cartItem), which, in turn, update two hidden fields on the form form-cart-delete, and also triggers a form submission. This form will call the server to update the cart, and update the cartItemsList object with the response.

  2. The amp-list component contains the expression [src]="cartItemsList.items", so that, when the cartItemsList object changes, as a result of the previous action, the list gets refreshed with the content of the updated cart.

<amp-list credentials="include"
  <template type="amp-mustache"
      <h3>Your Basket is Empty. </h3>
        <div class="item-headline">{{name}} - {{price}}</div>
        <div class="item-details">
          <div class="item-attribute">Color: {{color}}</div>
          <div>Size: {{size}}</div>
          <div>Qty: {{quantity}}</div>
          <button type="button"
            on="tap: AMP.setState({cartItem:
                                { id: '{{id}}',
                                  size: '{{size}}'
                                }}), form-cart-delete.submit">X</button>

Delete Items Form

As said, we use amp-form to send an XHR POST request to /delete-cart-item:

  1. The form contains two hidden input fields, bound to the cartItem object's variables. When the remove button is clicked, this object gets updated with the details of the item to remove from cart, so the form can send them on the call to the server.
  2. The form updates the cartItemsList with the response from the server, so that amp-list can be refreshed with the contents of the updated cart.
<form id="form-cart-delete"
  on="submit-success: AMP.setState({
              cartItemsList: event.response
  <input type="hidden"
  <input type="hidden"

Cart List Object

This object will be updated after the removal of an item, with the contents of the updated cart.

<amp-state id="cartItemsList">
  <script type="application/json">


Cart Item Object

This object acts as a proxy between the action of removing items, and the form submission.

<amp-state id="cartItem">
  <script type="application/json">

Need further explanation?


Go to Stack Overflow
An unexplained feature?


Edit sample on GitHub