getInventory()

in MIG - Migrating Applications to the Cloud/MIG40/src/frontend/src/ProductTable.js [56:90]


  getInventory() {
    if (this.interval > Date.now()) {
      requestAnimationFrame(this.getInventory);
      return;
    }

    const nums = Array.from({ length: this.state.stop - this.state.start + 1 })
      .map((_, index) => {
        const i = index + this.state.start;
        // attempt to fix off by one error
        return (this.state.rows[i] && this.state.rows[i].id) || 0;
      })
      .join(",");
    const start = Date.now();
    fetch(
      `${process.env.INVENTORY_SERVICE_BASE_URL}/api/inventory?skus=${nums}`
    )
      .then(data => {
        this.props.setTiming(null, Date.now() - start);
        return data.json();
      })
      .then(skus => {
        skus.forEach(sku => {
          const item = this.state.rows.find(p => p.id == sku.sku);
          if (item) {
            item.inventory = sku.quantity;
          }
        });

        this.forceUpdate();
        this.interval = Date.now() + 5000;
        requestAnimationFrame(this.getInventory);
      })
      .catch(console.error);
  }