If you want to append an array to another array, try this instead:
this.products.push.apply(this.products, response.data);
Hello all,
I currently have an API endpoint that returns a paginated list of products.
When my Vue component is ready, it makes a call to my endpoint and stores the the data in an array. Here's an example of my response from the products endpoint:
{
"data": [
{
"id": 1,
"name": "Willard Treutel",
"price": 39320
},
{
"id": 2,
"name": "Douglas West",
"price": 3235
},
{
"id": 3,
"name": "Annabell Boyer",
"price": 22481
}
],
"meta": {
"pagination": {
"total": 50,
"count": 5,
"per_page": 5,
"current_page": 1,
"total_pages": 10,
"links": {
"next": "http://domain.dev/api/products/?page=2"
}
}
}
}
Note, I've removed a lot of data from the response for this thread.
And here's some working code - which fetches this page of products, stores them and fetches the next page endpoint (Shown as http://domain.dev/api/products/?page=2).
data: function() {
return {
nextPage: null
}
},
ready: function() {
this.getProducts();
},
methods: {
getProducts: function() {
this.$http.get('/api/products', function(response) {
this.$set('products', response.data);
this.nextPage = response.meta.pagination.links.next;
});
}
}
In my components template I have a button that when pressed, will fire another method I have set up which should fetch the products in that response, and append the existing products array. Here's what I currently have:
loadMore: function() {
this.$http.get(this.nextPage, function(response) {
this.products.push(response.data);
this.nextPage = response.meta.pagination.links.next;
});
}
My issue here is this, when the above method is fired - it just appears to store the array of objects it fetches, directly into the products when pushed.
Here's an visual explanation of what's happening. I'm simply clicking the button I mention above and here's the products array from Vue Devtools.

How can I correctly store the products I fetch when calling the loadMore() method? As it's currently just storing the entire array in products.
I've tried to include as much information as possible, but if I've missed anything - please do let me know!
If you want to append an array to another array, try this instead:
this.products.push.apply(this.products, response.data);
Please or to participate in this conversation.