Finishing the Cart

At MenuPage and DetailsPage add calls to addToCart function importing it first.

Create a new file

components/CartItem.js

import { removeFromCart } from "../services/Order.js";

export default class CartItem extends HTMLElement {
    constructor() {
        super();    
    }   

    connectedCallback() {
        const item = JSON.parse(this.dataset.item);
        this.innerHTML = ""; // Clear the element

        const template = document.getElementById("cart-item-template");
        const content = template.content.cloneNode(true);

        this.appendChild(content);    

        this.querySelector(".qty").textContent = `${item.quantity}x`;
        this.querySelector(".name").textContent = item.product.name;
        this.querySelector(".price").textContent = `$${item.product.price.toFixed(2)}`;
        this.querySelector("a.delete-button").addEventListener("click", event => {
            removeFromCart(item.product.id);
        })
      }
}

customElements.define("cart-item", CartItem);

Updating the Page

Then, at components/OrderPage.js add the following code

export default class OrderPage extends HTMLElement {

  constructor() {
      super();
  
      this.root = this.attachShadow({ mode: "open" });    
      const styles = document.createElement("style");
      this.root.appendChild(styles);
      const section = document.createElement("section");
      this.root.appendChild(section);

      async function loadCSS() {
        const request = await fetch("/components/OrderPage.css");
        styles.textContent = await request.text();
      }
      loadCSS();
  }   

  connectedCallback() {
    window.addEventListener("appcartchange", () => {
      this.render();
    })
    this.render();
  }

  render() {
    let section = this.root.querySelector("section");   
    if (app.store.cart.length==0) {     
      section.innerHTML = `
          <p class="empty">Your order is empty</p>
      `;
    } else {
      let html = `
          <h2>Your Order</h2>
          <ul>
          </ul>
      `;
      section.innerHTML = html;

      const template = document.getElementById("order-form-template");
      const content = template.content.cloneNode(true);
      section.appendChild(content);

      let total = 0;
      for (let prodInCart of app.store.cart) {      
          const item = document.createElement("cart-item");
            item.dataset.item = JSON.stringify(prodInCart);
          this.root.querySelector("ul").appendChild(item);
        
          total += prodInCart.quantity * prodInCart.product.price;
      }
      this.root.querySelector("ul").innerHTML += `
            <li>
                <p class='total'>Total</p>
                <p class='price-total'>$${total.toFixed(2)}</p>
            </li>                
        `;      
    }
  }
}
customElements.define("order-page", OrderPage);