Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

david001's avatar

vue js push is not a function

Hi, i am making a small app with laravel and vuejs. I'm getting an error, the push is not a function when I clicked an add to cart button. Everything is working here fine but methods addProductToCart gives error push is not a function. when I first click add product to cart button it gives that error and once I refresh the page I can see a product in cart and again if click adds to cart button this time error is not seen, works perfectly. when cart[] is empty it gives error push is not a function, but when cart[] has at least one element I don't get that error. Any help would be greatly appreciated.


<div v-for="product in products" >
          <div class="card" >
            <div class="card-header">{{product. name}}</div>

            <div class="col-md-4">

                <div class="card-body">
                        <img :src="product.image">
                        <p>{{product.price}}</p>
                        <p>{{product.category_id}}</p>
                    </div>
                <button class="btn btn-primary"  @click="addProductToCart(product)">
                 
                </button>
                </div>

            </div>
        
     
        
        </div>


<script>
    export default {

        data:function(){
            return {
                products:[],
                
                cart:[]

            }

        },
        methods:{


            addProductToCart(product){
                var app = this;
                      
                    app.cart.push(product)


                axios.get('/cart',{

                     params: {
                        product: product,
                    }

                }).then((response)=>{

                });

            
            }
,
 mounted() {
                console.log('Product mounted.')
                var app = this;
                axios.get('/products')
                    .then(function (resp) {
                        app.products = resp.data;
                    })
                    .catch(function (resp) {
                        console.log(resp);
                        alert("Could not load companies");
                    });

                   
//if i replace this part it works fine
                    axios.get('/list')

                    .then(function (resp) {
                        app.cart = resp.data
                        
                    })

            }
        
            }
</script>

my /products return data in below format


[
{
id: 1,
name: "Keyshawn McDermott Sr.",
description: "Error aut quia id dolorem est aut doloribus nesciunt. Quod nihil tenetur ea id voluptas molestias id. Debitis amet dolor est fugiat sed autem.",
category_id: 1,
price: 59,
image: "http://loremflickr.com/400/300?random=36",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
},
{
id: 2,
name: "Marlene Reichert",
description: "Debitis asperiores sed sit assumenda unde quo natus. Consequatur est labore tenetur quae. Eius distinctio ea omnis aspernatur porro earum quae.",
category_id: 3,
price: 76,
image: "http://loremflickr.com/400/300?random=71",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
},

{
id: 19,
name: "Syble Turner PhD",
description: "Consequatur aut et eos sunt blanditiis vel. Tempore ut labore enim eos. Quia cupiditate vel nihil eius repellendus.",
category_id: 9,
price: 231,
image: "http://loremflickr.com/400/300?random=18",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
},
{
id: 20,
name: "Dayana Macejkovic",
description: "Sit quo qui et consequuntur culpa. Quia occaecati sunt sequi recusandae est. Ea autem doloremque odio dolores ut.",
category_id: 1,
price: 285,
image: "http://loremflickr.com/400/300?random=1",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
}
0 likes
19 replies
rameezisrar's avatar

@david001

Why are you sending the params with a get request? I think you want to send a post request once the user hit submit checkout. try this

addProductToCart(product){
                var app = this;
                      
                    app.cart.push(product)

console.log(product);

}
                

Are you getting the product on console?

bobbybouwmann's avatar

This part


var app = this;
                      
app.cart.push(product)

Can be converted to this:

this.card.push(product)

In general this should just work out of the box! Because you reassign this to app you might get this issue!

david001's avatar

@rameezisrar No, i'm not getting anything in console. when i submit button i got this error

app.js:38298 [Vue warn]: Error in v-on handler: "TypeError: app.cart.push is not a function"

found in...```
tykus's avatar

Something is changing what cart is; can you open the Vue devtools and see what cart is whenever the error occurs?

rameezisrar's avatar

@david001 I think you are missing the template tags

<template>

<div v-for="product in products" >
          <div class="card" >
            <div class="card-header">{{product. name}}</div>

            <div class="col-md-4">

                <div class="card-body">
                        <img :src="product.image">
                        <p>{{product.price}}</p>
                        <p>{{product.category_id}}</p>
                    </div>
                <button class="btn btn-primary"  @click="addProductToCart(product)">
                 
                </button>
                </div>

            </div>
        
     
        
        </div>

</template>
david001's avatar

i have in full code. That was part of code

rameezisrar's avatar

@david001 try this


<div v-for="(product, index) in products" :key="product.id" >
          <div class="card" >
            <div class="card-header">{{product. name}}</div>

            <div class="col-md-4">

                <div class="card-body">
                        <img :src="product.image">
                        <p>{{product.price}}</p>
                        <p>{{product.category_id}}</p>
                    </div>
                <button class="btn btn-primary"  @click="addProductToCart(product)">
                 
                </button>
                </div>

            </div>
        
     
        
        </div>


tykus's avatar
cart:""

that'll be why the push is not working - what else modifies cart??

david001's avatar

@bobbybouwmann

Still i got same error, push is not a function in dev tool i can see


cart:""
 products:Array[20]
tykus's avatar

You are initialising the cart as an empty array; but in devtools it is an empty string; so, something is changing it. Are we seeing all of the methods? Do you have some method to empty the cart perhaps?

david001's avatar

@tykus yes your guess is right: in mounted i have this part:


   axios.get('/list')

                    .then(function (resp) {
                        app.cart = resp.data
                        
                    })

i need above part because when user refresh the page all data will be lost. so i use push to show live data in page and above to fetch same data even after page reloaded. Anyway other ways where i can show data to user as shown as added and remain same even after page reloaded

my mounted



mounted() {
                console.log('Product mounted.')
                var app = this;
                axios.get('/products')
                    .then(function (resp) {
                        app.products = resp.data;
                    })
                    .catch(function (resp) {
                        console.log(resp);
                        alert("Could not load companies");
                    });


//if i replace this part it works fine
                    axios.get('/list')

                    .then(function (resp) {
                        app.cart = resp.data
                        
                    })

            }
        }
tykus's avatar

So the response data is empty; if you check for that you can ensure the cart is still an array

axios.get('/products').then(function (resp) {
    app.products = resp.data || []; // an empty string is falsey so cart gets an empty array instead.
}).catch(function (resp) {
    console.log(resp);
    alert("Could not load companies");
});

If you own the api endpoint, you could otherwise ensure that the response is an empty JSON array

david001's avatar

I made changes according to yours. But still same error, push is not a function


mounted() {
                console.log('Product mounted.')
                var app = this;
                axios.get('/products')
                    .then(function (resp) {
                        app.products = resp.data || [];
                    })
                    .catch(function (resp) {
                        console.log(resp);
                        alert("Could not load products");
                    });

                    axios.get('/list')

                    .then(function (resp) {
                        app.cart = resp.data
                        
                    })

            }
tykus's avatar
tykus
Best Answer
Level 104

Sorry, I edited the wrong part:

axios.get('/list').then(function (resp) {
    app.cart = resp.data || [];
})

Leave the products assignment as it is, to ensure you always are iterating over an array.

1 like

Please or to participate in this conversation.