Mapping Data with Ajax in VueJs

When a Vue page is loaded, I make an Ajax call in the mounted() event to retrieve data. In order to reconstruct the existing Pager object with all its required parameters, I create a new Pager instance each time.

If I don't do this, vm.Pager remains just an Object without necessary methods, causing it to fail the prop type check that is passed to it.

axios.post("/Home/GetList", vm.Pager)
.then(function (result)
{
    var p = result.data.Pager;
    vm.Pager = new Pager(p.PageSize, p.CurrentRecord, p.TotalCount);
    //more operations on Pager fields
    vm.ItemList = result.data.ListItems;        
})
.catch(function (error)
{
    alert(error); 
});

In knockoutjs, there was a useful mapping function where you could specify the types to map without re-creating the object. This was especially handy for complex or nested Ajax data.

Is there a more efficient way to achieve this in Vue (or javascript) so that the type mapping from Ajax data can be done without the need to reconstruct the object?

Answer №1

One option is to create your own mapping function.

methods: {
  mapDataToProps (responseData, map) {
     responseData.forEach((item, key) => {
       let mapperVal = map[key]
       if (typeof mapperVal === 'string') {
         this.$set(this, map[key], item)
       } else if (typeof mapperVal === 'function') {
         this.$set(this, key, map[key](item))
       }
     })
  }
}

Then, in your AJAX request:

axios.post("/Home/GetList", vm.Pager)
.then(function (result)
{
this.mapDataToProps(result.data, {
ItemList: 'ListItems',
Pager: (p) => new Pager(p.PageSize, p.CurrentRecord, p.TotalCount)
})      
})

Answer №2

In my exploration, I have discovered two methods to update the viewmodel effectively:

Object.assign(vm.Pager, result.data.Pager);

Alternatively,

// import _ from 'lodash'
_.merge(vm.Pager, result.data.Pager);

Despite their effectiveness, these methods do not trigger the watch method in the nested ListPager control that receives the Pager object.

To address this issue, I found a solution after referencing the documentation on reactivity in Vue.js VueJs: Reactivity in Depth - Change Detection Caveats.

vm.Pager = Object.assign(new Pager(), vm.Pager, result.data.Pager);

This approach involves creating a new Pager object while maintaining Vue reactivity, offering scalability for more complex solutions in the future.

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

Using React and Material-UI to dynamically populate a table with data retrieved from

Material ui table utilizes data in a specific format. rows: [ createData(1, "dashboard", "details"), createData(2, "product", "product details"), ].sort((a, b) => (a.id < b.id ? -1 : 1)) When the API responds with data stored in st ...

The Jquery Post Method functions smoothly on a local environment, however encounters issues when deployed on a

I am facing an issue with a simple function that is supposed to write on a file. It works perfectly fine on my local server, but when I deploy it on the server, it fails to write on the file. What could be causing this problem? foo.php <? if (isset($_ ...

Steps for obtaining a CSV or PDF file as the response to an AJAX request

Currently, my project is built on Django. I am in need of a solution to receive a PDF, CSV, or XLS file as a response after submitting a form via AJAX. While the file is successfully received when I submit the form normally, it does not display the downl ...

The use of the jQuery clone() method in conjunction with jQuery TABS allows for the display of cloned fields

I've implemented jQuery tabs with the following code structure: <ul class="tabNavigation" id="tabs"> <li><a href="#AAA">AA</a></li> <li><a href="#BBB">BBB</a></li> </ul> ...

Randomly choose one of 5 pages and insert an HTML element at different intervals using JavaScript, jQuery, MySQL, or PHP

Suppose we have the following HTML element: <img src="icon.png"> Our website consists of 5 pages: index.php products.php register.php about.php terms.php How can we randomly place this HTML element on one of the pages, ensuring it stays there for ...

Is there a way to dynamically add an option to multiple select boxes and then only redirect the browser if that specific option is chosen using jquery/js?

Presently, this is the code I am working with. The URL validator is specifically included because there was an issue with redirection occurring on any option selected, however, I only want a redirect to happen when the options I add with jQuery are clicked ...

What is the correct way to utilize jquery's getJSON function?

<html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#hidebtn").click(function() { ...

Using MSAL for secure authentication and authorization in React.js

I am new to React and currently working on implementing Single Sign On Authentication in my React App. Goals: Create a login page where users can enter their email address When the user clicks sign-in, display the SSO popup (using Azure AD) for acceptin ...

Encountering the error "Uncaught reference error: $ is not defined" despite ensuring that scripts are loading in the correct order. However, the scripts work from the

Encountering an Issue: "Uncaught ReferenceError: $ is not defined" Whenever I try to utilize $('#someid') in my custom JavaScript code within an Electron app. All scripts are properly arranged in my HTML file: <script type="text/javascri ...

Retrieving specific rows from an array in AngularJS based on certain conditions

I am dealing with an array that has the following structure: var hospitals=[{"distric_id":"1","type":"c","details":[{"name":"hello","address":"hello","number":"686678"}]}, {"distric_id":"1","type":"g","details":[{"name":"hello","address":"hello","numbe ...

Implement a function to trigger and refresh components in various Vuejs2 instances simultaneously

I currently have index.html with two Vue instances in different files: <!DOCTYPE html> <html lang="en"> <body> <div id="appOne"> </div> <div id="appTwo"> </div> </body> </html ...

Adding a function as a parameter in TypeScript while utilizing prop destructuring in a React function component

When using React JS, it's possible to pass the function handleClick as a parameter from the parent component to the child component like this: Parent: const testData = { id: 1, title: 'Tesco' }; const Home = () => { const handl ...

Extend GridView cell for file preview and download

Within my gridview, there is a column labeled "File Name" which includes the names of various files. I am looking for a way to click on a specific file name and be able to view its content as well as save or download the file. I am open to all suggestions ...

The use of Next.js v12 middleware is incompatible with both node-fetch and axios

I am facing an issue while developing a middleware that fetches user data from an external endpoint using Axios. Surprisingly, Axios is not functioning properly within the middleware. Below is the error message I encountered when using node-fetch: Module b ...

What is the process for accessing the contents of various versions of an S3 object?

In my Python boto3 code, I have the following snippet to retrieve versions of an S3 object along with its content: versions = s3.Bucket(bucket).object_versions.filter(Prefix=key) for version in versions: obj = version.get() data = obj.get('Bod ...

unable to see the follow button in the website's Vue component

I am struggling to locate the button on my website Let's take a look at the FollowButton.Vue code below: <template> <div> <button class="btn btn-primary ml-4">Follow Me Now</button> </div> </temp ...

Comparing Fetch Request and WebSocket: Determining the Quickest Option

When sending the same data in both Fetch and WebSocket, there is a noticeable speed difference: HTTP takes 29 seconds to transfer around 200 MB. WebSocket takes 6 seconds to transfer around 200 MB. An Interesting Observation: Why does WebSocket outperfo ...

Tips for implementing PHP Instagram Signature using AJAX

I'm facing a challenge with the latest Instagram API, which now requires an Enforced Signed request that includes both an Access Token and Client Secret to generate a Signature. If anyone could spare some time to help me out, I would greatly apprecia ...

To Vue3, or not to Vue3: should I mount the body element?

With the introduction of Vue3, the app root mount element is no longer replaced; instead, the innerHTML of the mount point is updated. This allows for mounting the body element, which was attempted by many in Vue2. However, is it advisable to use the bod ...

Enhance your website by adding a <select> element using an AJAX call that

Encountering challenges in dynamically generating <select> elements and then populating them with values from an XML file. The jQuery script appends a <div> containing a select element and adds options based on the data obtained from XML. Thi ...