title: How to set state of cart when no items?
body: <p>In my E-Commerce project, the products are stored in localStorage. componentDidMount() gets all these products from localStorage and displays it. How to state the state or condition when no products are available.</p>
  
  <pre><code>componentDidMount = () =&gt; {
          this.setProducts();
  
          // Gets all products in cart from localStorage
          this.setState(
                  () =&gt;{
                     return {cart: JSON.parse(localStorage.getItem('myCart'))}
                  },
                  () =&gt; {
                      this.addTotal()
                  })
         // How to set the condition when no products in Cart?   
      }
  
  // Set all the products on Main Page
  setProducts = () =&gt; {
         let tempProducts = [];
  
         storeProducts.forEach(item =&gt; {
              const singleItem = {...item};
              tempProducts = [...tempProducts, singleItem];
         }); 
         this.setState(() =&gt; {
          return {products: tempProducts};
         });
      };
  
  // Here products are added to cart and stored in localStorage
  addToCart = (id) =&gt; {
          let tempProducts = [...this.state.products];
          const index = tempProducts.indexOf(this.getItem(id));
          const product = tempProducts[index];
          product.inCart = true;
          product.count = 1;
          const price = product.price;
          product.total = price;
          this.setState(() =&gt; {
              return { products: tempProducts, cart: [...this.state.cart,
              product] };
          },
          () =&gt; {
              this.addTotal();
              localStorage.setItem('myCart', JSON.stringify(this.state.cart))
          });
      }
  </code></pre>
  
  <p>I have also tried to make following changes, but, no effect. In componentDidMount()</p>
  
  <pre><code>componentDidMount() {
        if(this.state.cart.length &gt; 0) {
              this.setState(
                  () =&gt;{
                     return {cart: JSON.parse(localStorage.getItem('myCart'))}
                  },
                  () =&gt; {
                      this.addTotal()
                  })
          } else {
              this.setState(() =&gt; {
                  return {cart:[]}
              })
          }
  
  }
  
  // Clear Cart
  clearCart = () =&gt; {
          this.setState(() =&gt; {
              return {cart:[]}
          }, () =&gt; {
              this.setProducts();
              this.addTotal();
  
          })
          localStorage.removeItem('myCart')
      }
  </code></pre>
  
  <p>When I remove code of setState (shown in the beginning) from componentDidMount() displays empty cart message, which is expected else, if the cart is cleared and refreshed browser throws 'cart.length' error. Any possible solution?</p>