Ionic 3 with storage

#1

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);
    });
#2

Hello, can you show me cart variable declaration please?

#3
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



#4

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
#5

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

#6

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

#7

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

#8

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);
});
#9

isnt working :frowning:

#10

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');
  }