What is the correct method for adding a JSON array to an existing data array in Vue.js after receiving an Axios response?

I have a question related to JavaScript, specifically in the context of Vue.js, Laravel & Axios.

How can I push one JSON array into another JSON array without nesting it? When I try to push the secondary array into the primary array, it ends up nested (as shown in the screenshot). I need both arrays to be part of the same array structure.

Could this be a simple indexing issue? I've heard that using concat can achieve this, but I prefer to use push because I have a "load more" button and want to append new data to the existing array from the bottom for smoother loading experience, similar to Pinterest's infinite scroll functionality where new results are added at the end.

(Please note that the code provided is simplified for clarity)

I start with an empty array in the data property:

data () {
    return {
        articles: [],
    }
},

Initially, on page load, the articles array gets populated with JSON data.

created() {
axios.get(url)
.then(response => {
this.articles = response.data.data;
});
},

Then, when I want to 'load more' results using a method:

loadMore() {
axios.get(url)
.then(response => {

console.log('Current state of articles array:')
console.log(this.articles)

this.articles.push(response.data.data)

console.log('Newly fetched array data:')
console.log(response.data.data)

console.log('Updated array after pushing new data:')
console.log(this.articles)

});
}

Console log reference link: https://i.sstatic.net/941eM.png

If done correctly, the resulting articles array should have a length of 10 (5 + 5) after appending.

Both responses are accurate and contain valid JSON. I managed to make it work by using concat to merge the arrays. However, I found this method undesirable as it reloads the entire array.

Answer №1

If you prefer not to use .concat, which is a simple and effective method, you can experiment with the alternative below:

const numbers = [1,3,4,5];
numbers.push(...[6,7,8,9);
console.log(numbers); // now it will display [1,2,3,4,5,6,7,8,9]

Answer №2

After receiving advice from both @noa-dev and @Shilly, I implemented the use of concat in the following way. The response had to be stored in a variable for the promise to work properly. Thank you for your help.

var new_array = response.data.data
this.articles = this.articles.concat(new_array)

I also learned how Vue does not actually replace the array when using concat! Check out more information here: https://v2.vuejs.org/v2/guide/list.html#Replacing-an-Array

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The lifecycle of a React state in a filtering component

Seeking guidance on handling state updates in a component designed for filtering purposes (such as selecting dates, min/max values, etc). My current setup is as follows: onMinDateChange(minDate) { this.setState({minDate}); }, onMaxDateChange(maxDate) ...

After the completion of the AJAX request, navigate to the bottom of the specified

I have come across a solution on how to scroll to the bottom of a div here. However, it seems that it is not working for me, the same goes for autofocus. I suspect the problem lies in the fact that I am making an AJAX call, and it is not functioning prope ...

The Resharper guideline "Function Parameter" doesn't allow the usage of AngularJS service names

I have a question regarding naming conventions in my AngularJS app. Currently, all my service names start with an uppercase character. However, I am facing an issue where service parameters must match the service name, but Resharper's JavaScript "Func ...

The npm script isn't executing

In my package.json file, I have the following script: "scripts": { "build": "browserify app/components/main.js -o build/js/app.js -d" } Executing this command from the shell works fine and the file is created successfully. But when I try to run npm bui ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

Can IFrames be loaded asynchronously? If not, what is the reason for this error to happen?

Note: After running some tests, it seems that iframes load asynchronously (although not completely certain). To address this issue, I implemented a solution by delaying the function call for 700 milliseconds, which proved to be effective. This led me to be ...

Issue Encountered with FabricJS: Unable to Execute 'drawImage' with Image Subclass

I'm working on a project that requires me to add images of different types to a canvas, save them as JSON, and then load them again. The unique property needed for each type is simply the differentiation in type. To achieve this, I have created a new ...

Displaying 2 unique div elements with distinct buttons on a single blade using Laravel and VUE

Hello everyone! I have a puzzle for you: I possess one blade, but when I am given two distinct buttons: <div class="col-md-12"> <button v-on:click="isHidden = !isHidden" type="button" class="w3-btn ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...

Enhance your ASP .NET Core development with intelligent React props suggestions

Looking to enable intellisense for React props, previously achieved by passing ViewModel to Razor views (.cshtml) using @model namespace.WeatherVM. This allowed easy access to properties like @Model.TemperatureF, with intellisense providing available optio ...

Simulating an uploaded file containing data

In my current Laravel project, we are implementing GraphQL using Lighthouse as our backend API. Some of our endpoints support file uploads, which we have successfully tested. As we work on a new endpoint that also requires file upload functionality, we fa ...

Importance of xpath:position and xpath:attribute

I'm currently developing a recording tool using JavaScript that is comparable to Selenium. When it comes to Playback, I require the XPath position and its attributes (shown in the screenshot below from Selenium). Can anyone provide guidance on how to ...

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

Utilizing mouseover and mouseout in place of the :hover selector

In my latest project, I am experimenting with emulating the CSS :hover pseudoclass using a .hover class that is toggled on and off during the mouseover and mouseout events. I'm curious about how this may impact performance and what noticeable diffe ...

Utilizing Vue.js to pass a slot to a customized Bootstrap-Vue Table component

I am currently in the process of developing a wrapper for the bootstrap-vue Table component. This particular component utilizes slots to specify cell templates, similar to the following example: <b-table :items="itemsProvider" v-bind="options"> ...

"Enhancing user engagement in ThreeJS: a guide to incorporating interactivity

After successfully rendering a model in ThreeJS, my next task is to incorporate interactivity by: Coloring specific parts of the model based on user input. Implementing a feature where clicking on any part of the model triggers it to be highlighted. As ...

How can you easily reuse an Ajax method in Vue.js by passing a Vue data array name as an argument?

After dedicating 9 hours to learning Vue.js, I have ventured into using it with JQuery Ajax. My challenge lies in making the last argument work as intended. Passing an array name expected to exist in vue data: {... seems to yield no results. Update: I hav ...

Implement the scope change in an Angular controller by utilizing controllerAs functionality

I am facing an issue with my controller setup as shown below: angular .module('app.core') .controller('TestController', TestController); TestController.$inject = ['$timeout', '$interval']; function TestControl ...

What is the process for downloading a blob using an input field?

Can you help me figure out how to download a blob into an input field? Here is the HTML code I have: <img id="image" src="${pageContext.request.contextPath}/image/accaunt/user?${nowDate.time}"/> <label id="text-add-photo" for="img-input">repl ...

Check out our website's event countdown timer featuring a server-sided event tracking system

Currently, I am in the process of developing a website and have the requirement to incorporate a timer on one of the pages. The goal is for the timer to count down from a specified time, such as DD::hh:mm 02:12:34, until it reaches zero. Once the countdown ...