Ionic 3 with storage

I’ve tried to save my cart items in storage. At first it worked perfectly but suddenly when i tried again its throwing me an error this.cart.push() is not a function.

Unable to figure out what went wrong? Please help!!

this.storage.get('products').then((data) => {
      if (data == null) {
        data = [];
      }
      this.cart = data;       //re-initialize the items array equal to storage value
      this.cart.push(this.cartItem());
      return this.storage.set('products', this.cart);
    });

Hello, can you show me cart variable declaration please?

cart: any;

addToBag() {
    this.storage.get('products').then((data) => {
      if (data == null) {
        data = [];
      }
      this.cart = data;       //re-initialize the items array equal to storage value
      this.cart.push(this.cartItem());
      this.storage.set('products', this.cart);
    });
    console.log(this.cart);
    this.viewCtrl.dismiss(
      this.cartItem(),
    );
    this.toaster('Added To Cart');
  }

cartItem() {
    let bag = {
      size: this.selectedSize,
      item_id: this.items.item_id,
      merchant_id: this.items.merchant_id,
      price: this.selectedSizePrice,
      AddOn: this.selectedAddOn,
      AddOnPrice: this.addOnPrice,
      Spicy: this.selectedSpicy,
      AddonTotalPrice: this.getTotal(),
      itemTotal: this.grandTotal(),
      itemName: this.items.item_name,
      qty: this.quantity,
      cartTotal: this.total(),
    }
    return bag



You should initialize the cart variable as an Array first. The error says that you cannot push because you haven’t declared it as an array. Your are pushing into unknown variable. Try this:

cart: Array<{size: number, item_id: number, merchant_id: number, price: number, AddOn: string, AddOnPrice: number, Spicy: string, AddonTotalPrice: number, itemTotal: number, itemName: string, qty: number, cartTotal: number}>=[];

Hope this helps you.

1 Like

Should i declare this cart variable above constructor? or with the storage method?

Declare it as a global error. As you declared now.

in console.log its showing me [] not the value

if you log an array that’s what it displays right. Try logging by array index.

console.log(this.cart[0]);

or

this.cart.forEach((element)=>{
console.log(element);
});

isnt working :frowning:

Found the solution :slight_smile:


getData() {
    return this.storage.get('products');
  }

addToBag(){
    this.getData().then((products: any[]) => {
      if (products) {
        products.push(this.cartItem());
        console.log(products);
        return this.storage.set('products', products);
      }
      return this.storage.set('products', [this.cartItem()]);
    });
    this.viewCtrl.dismiss(
      this.cartItem(),
    );
    this.toaster('Added To Cart');
  }