Preparing data in the Vuex Store efficiently for an AJAX request

Dealing with a Vuex store that holds around 30 fields has been quite the challenge for me over the past couple of days. I've been struggling to properly gather the data before sending it through an AJAX post method. Being aware of the reactivity of Vuex properties, I've encountered some issues along the way. After conducting various tests to make sure the data is correctly passed to my Asp.Net controller, here's what I discovered.

Below are logs showing the state before and after the AJAX call.

Initially, I tried using a hardcoded object, which surprisingly worked fine for testing purposes:

var obj = {
  'essay': 'hardcoded nonsense is nonsense',
  'age': 28
}

My subsequent attempt involved directly passing store.state as the data object, but this resulted in passing unnecessary data and didn't work well with larger objects.

Then, I attempted to convert it to JSON hoping to get rid of unwanted data (idea sourced from here)

var jsonData = JSON.parse(JSON.stringify(store.state))

A friend recommended using _lodash to filter out extra content, but unfortunately, it ended up being null upon reaching my .Net controller (source idea from here)

var lodashData = _.omitBy(store.state, _.isNil)

Despite all the logs indicating success, only the first two methods actually transmitted any data to my controller.

What would be the correct approach for handling this kind of situation?

var jsonData = JSON.parse(JSON.stringify(store.state))

var lodashData = _.omitBy(store.state, _.isNil)

export default {
  name: 'demo-submit',
  methods: {
    submit () {
      console.log('hardcoded object', obj)
      $.post('/Contest/UploadInfo', obj)
        .done(function (response, status, jqxhr) {
        console.log('success: hardcoded obj', obj)
      })
      .fail(function(jqxhr, status, error) {
          console.log('error: hardcoded')
      });

      console.log('store.state', store.state)
      $.post('/Contest/UploadInfo', store.state)
        .done(function (response, status, jqxhr) {
        console.log('success: store.state', store.state)
      })
      .fail(function(jqxhr, status, error) {
          console.log('error: store.state')
      });

      console.log('jsonData', jsonData)
      $.post('/Contest/UploadInfo', jsonData)
        .done(function (response, status, jqxhr) {
        console.log('success: jsonData', jsonData)
      })
      .fail(function(jqxhr, status, error) {
          console.log('error: jsonData')
      });

      console.log('lodashData', _.omitBy(store.state, _.isNil))
      $.post('/Contest/UploadInfo', lodashData)
        .done(function (response, status, jqxhr) {
        console.log('success: lodashData', lodashData)
      })
      .fail(function(jqxhr, status, error) {
          console.log('error: lodashData')
      });
    }
  }
}

Answer №1

Ensure that your JSON.parse and JSON.stringify are functioning properly by checking the structure of your state. Kindly share your state code for further assistance.

If these functions are not working as expected, you can always take a simpler approach in certain cases like this:

const payload = {
  age: store.state.age,
  essay: store.state.essay
}

In case you have numerous fields to deal with, consider creating a function like the following:

const toPlainObject = (state, keys) => {
  const obj = {}
  keys.forEach(key => {
    obj[key] = state[key]
  })
  return obj
}

const payload = toPlainObject(store.state, ['age', 'essay'])

If you prefer a more dynamic approach without specifying fields, utilize for .. in loop to iterate through the entire state object.

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

Could this truly be jQuery in action?

Once more, here is some code snippet: audioElement.addEventListener('ended', function() { $('span#pause').fadeOut('slow'); $('span#play').delay(1500).fadeIn('slow'); }); I believe that "addEventLi ...

Navigate through the list of options by scrolling and selecting each one until the desired element is

Hey, I've got this AngularJs directive that selects an item based on the "key-pressed" event, and it's working perfectly. The issue arises when there is a scroll bar since the elements get hidden, making it difficult for me to see them. You can ...

Why are the radio buttons not aligned with the text in the center?

Currently, I am in the process of building a form that includes radio buttons. However, I've encountered an issue where the text next to the radio buttons appears on a different level than the buttons themselves. How can I go about fixing this partic ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

React developer server is failing to automatically refresh the code

I've encountered an issue with react-dev-server where changes I make to the code do not reflect on the app itself even after refreshing (not hot-loading). I've tried setting up my own project as well as using Facebook's Create-react-app, whi ...

What is the most effective way to reset the state array of objects in React JS?

I'm facing a challenge in resetting an array of objects without having to rewrite the initial state value again. Initial state const [state, setState] = useState([ {name: 'abc', age: 24}, {name: 'xyz', age: 20} ]) Is there a metho ...

Troublesome GSP: JavaScript not functioning properly in Gr

I am experiencing an issue with the JavaScript code I have. Here's my code: <script type="text/javascript"><!-- ​$(function () { $('#add').click(function() { $(this).before($('select:eq(0)').clone()); ...

How can I ensure that I only include a field in a JavaScript object if the value is not null?

In my current setup, I am utilizing mongoose to write data to a MongoDB collection while ensuring there are no null fields. Default values have been set in the document for this purpose. During an update function call, certain fields may be null but I do n ...

utilizing array.map() to nest multiple layers of arrays

I am facing a challenge with a JavaScript array structure that contains three top-level objects. Each of these objects has an "teamLineup" array, which in turn holds two more objects named "team". These "team" objects have another array called "starters", ...

I am looking to create a cascading dropdown list in C# MVC that pulls data from various SQL tables. How can I achieve

I am currently working on a C# MVC web application and facing a challenge in implementing a cascading drop-down list. While I have come across various articles discussing this topic, the uniqueness of my requirements makes it difficult for me to figure out ...

Using the createElement method in React to restart a GIF animation

In my React project, I'm attempting to develop a function that generates a new element displaying a gif for one loop before removing it. My current approach looks like this: function playGif() { var gif = document.createElement('img') ...

Unexplained disappearance of div element in Vue Router's Navbar

I have been working on integrating a Vue Router into my navbar and everything seemed to be going well. You can check out the code here. The navigation menu I created works perfectly, allowing users to navigate between the home template and about template w ...

Tabs within the AutoComplete popup in Material-UI

Would it be feasible to showcase the corresponding data in the AutoComplete popover using Tabs? There could be potentially up to three categories of data that match the input value, and my preference would be to present them as tabs. Is there a way to in ...

Decoding JSON Data in Google Web Toolkit

In our development, we have utilized the GWT Platform along with GWTP client and rest web services within a GUICE container. The invocation of rest services from the GWT client is achieved using JSONPRequestbuilder. I am curious to discover the most effec ...

The functionality of uploading files in Dropzone.js is not supported on Windows operating systems

I am currently working on a file uploader using dropzone functionality. I will share the code with you shortly, but first let me outline the problem: My setup consists of an Ubuntu machine running the server code in node.js using the multer library. The f ...

Exploring the potentials of AngularJs Datatables Promise and the ignited power of Ignited

I am currently facing an issue with populating a datatable in AngularJS. DataTables warning: table id=DataTables_Table_0 - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.n ...

Tips for checking form input validity prior to opening a modelDialog

After successfully validating all required form fields, I am trying to open a modal dialog. Although I have managed to validate the form, I am struggling to write the code that will trigger the opening of the modal dialog upon successful validation. Do y ...

In the realm of asp.net mvc, JSON remains a mysterious and undefined

When working with ASP.NET MVC 3, I have encountered an issue regarding JSON in my AJAX calls. The application runs smoothly on my development machine when using Visual Studio. However, after publishing the same application and trying to access it through a ...

Assistance with changing styles

Hey there, I could really use some assistance. I've created a style switcher, but I'm struggling to figure out how to replace the stylesheet properly. Currently, my code empties the <head> element when what I really need is for it to simply ...

Transitioning from webpack to vite with Vue.js for a Chrome extension development project

I am currently developing a Chrome extension using Vue.js. I have a project ready to start with, but it is set up with webpack. Within webpack, I have multiple entry points that result in the generation of HTML files and others with JavaScript only. Whil ...