Losing the attributes of an object is a common issue when utilizing axios in Vue.js

Recently, while working with axios, I've encountered a puzzling issue where some attributes of objects seem to disappear. Take a look at this snippet of code:

<template>
  <div>
    <v-message-box :data="mBox" />
    <v-data-table :headers="headers" :items="items" sort-by="calories" class="elevation-1">
      <template v-slot:top>
        <v-toolbar flat color="white">
          <v-toolbar-title>Complaint list</v-toolbar-title>
          <v-divider class="mx-4" inset vertical></v-divider>
          <v-spacer></v-spacer>
          <v-btn color="primary" @click="btnNewItem" dark class="mb-2">New Item</v-btn>
          <v-dialog v-model="dialog" max-width="500px">
            <v-card>
              <v-card-title>
                <span class="headline">{{ formTitle }}</span>
              </v-card-title>

              <v-card-text>
                <v-complaint :complaint="editedItem" />
              </v-card-text>

              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="blue darken-1" text @click="close">Cancel</v-btn>
                <v-btn color="blue darken-1" text @click="save">Save</v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>
        </v-toolbar>
      </template>
      <template v-slot:item.actions="{ item }">
        <v-icon small class="mr-2" @click="editItem(item)">mdi-pencil</v-icon>
        <v-icon small @click="deleteItem(item)">mdi-delete</v-icon>
      </template>
      <template v-slot:no-data>
        <v-btn color="primary" @click="initialize">Reset</v-btn>
      </template>
    </v-data-table>
  </div>
</template>

<script>
import vComplaint from "../create/v-complaint";
import Api from "@/api/Api";
import vMessageBox from "../commons/v-message-box";
import MessageBox from "../commons/messagebox.js";
import { mapGetters, mapActions } from "vuex";

export default {
  name: "v-complaint-table",
  data: () => ({
    dialog: false,
    headers: [],
    items: [],
    editedIndex: -1,
    editedItem: {},
    defaultItem: null,
    mBox: new MessageBox(),
  }),
  props: ["patient"],

  methods: {

    // Some functions ....
    editItem(item) {
      this.editedIndex = this.items.indexOf(item);
      this.editedItem = this.toObject(item);
      this.dialog = true;
    },

    deleteItem(item) {
      const index = this.items.indexOf(item);
      confirm("Are you sure you want to delete this item?") &&
        this.items.splice(index, 1);
    },

    close() {
      this.dialog = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      });
    },

    save() {
      let mBox = this.mBox
      if (this.editedIndex > -1) {
        let complaint = this.editedItem;
        Api()
          .put("/complaint_request", {
            complaint
          })
          .then(() => {
            console.log("Updated");
          })
          .catch(e => {
            mBox.showMessage("Error", e, "error");
            console.log(e);
          });
        Object.assign(
          this.items[this.editedIndex],
          this.toTemplate(this.editedItem)
        );
      } else {
        var complaint = this.editedItem;
        var _this = this
        console.log(this.editedItem)
        Api()
          .post("/complaint_request", {
            complaint
          })
          .then(respone => {
            _this.editedItem.id = respone.data;
            console.log(_this.editedItem)
            _this.items.push(this.toTemplate(_this.editedItem));
          })
          .catch(e => {
            mBox.showMessage("Error", e, "error");
            console.log(e);
          });
      }
      this.close();
    },
};
</script>

The first screenshot displays the attributes of this.editedItem:

https://i.sstatic.net/ZkxL2.png

However, in the second screenshot, we witness that some attributes like character and date are missing. These nested attributes have seemingly disappeared due to what seems to be an asynchronous issue possibly related to axios.

Here's a glimpse of the configuration for `Api.js`:

import axios from 'axios'

export default() => {
    return axios.create({
        baseURL: 'http://127.0.0.1:8000/api',
        //baseURL: 'http://192.168.137.1:8080/api',
        withCredentials: false,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'common': '',
            //'token': ''
        }
    })
}

Answer №1

When you use the close() function, you are actually assigning

this.changedItem = Object.assign({}, this.initialItem);

If you call this.close prior to the promise in the save function resolving, then this.alteredItem will be reset to this.initialItem, which likely does not include the date.

To avoid this issue, it's recommended to place the close function call within the .then callback of the promise.

Correction: update variable names

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

Is there a way to consolidate all Styled Components into a single file for exporting?

Imagine you have Styled Component JS files structured like this: LoginLogo.js export const LoginLogo = styled.img` margin-top: 150px; margin-bottom: 100px; margin-right: 100px; margin-left: 100px; height: 160px; width: 397px; `; FooterDiv.js ...

In JavaScript or jQuery, what is the most optimal method to swap out all instances of a specific string within the body content without altering the rest of the body text?

Is there a way to replace specific occurrences of a string within a web page's body without disrupting other elements such as event listeners? If so, what is the best method to achieve this? For example: Consider the following code snippet: <body ...

How to focus on a dynamically changing input box in Vue

In my form, users can input an email address and click a plus button to add another input box for a new email address. These input boxes are created by iterating over an array, so when the user clicks on the plus icon, a new entry is added to the array. W ...

How can the table attribute "name" be obtained and added as the file name for DataTables in the export feature?

Having multiple tables on my page using JQuery DataTables, I find it to be a useful library. I am looking to modify the file name for exporting the data on these tables. I have several DataTables on this page This is how I initialize my tables: $(docume ...

Performing calculations in each row of a dataframe using JavaScript

As someone who is just starting out with nodejs, I am interested in utilizing the dataframe-js library to iterate through rows and calculate the difference between each cell and the previous row. const columns = ["x","y","gap"]; const df= new DataFram ...

Vue 3 - Using Emit Functionality in a Reusable and Composable File

I'm trying to utilize the emit function in my file called useGoo.ts import Swal from "sweetalert2/dist/sweetalert2.js"; export default function useModal() { const { emit } = getCurrentInstance(); function myId() { emit('id&ap ...

What causes the issue of the 'MERGE' statement in Node.js resulting in the creation of duplicate nodes in Neo4j?

Currently tackling a Node.js project involving the creation of nodes in Neo4j using the 'MERGE' statement. Despite employing 'MERGE' to prevent duplicate nodes, duplicates are still being generated at times. Extensive searches through ...

What could be causing the regex to fail when trying to validate the header in a request?

Utilizing regex to enhance the response header, I am referring to this set of instructions: https://nextjs.org/docs/api-reference/next.config.js/headers The documentation explains how to incorporate Regex Path Matching, however, it seems to be ineffectiv ...

Inject external JSON data into the router

I need to incorporate dynamic routes from an external json file in my Nuxt application, which may change during runtime. More information on a similar topic can be found here. To achieve this, I have customized the default Nuxt router with my own logic. H ...

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 ...

Understanding the concept of Angular factories in Javascript

app.service('WeatherService', function($http) { var service = {}; service.getLocation = function() { return $http.jsonp("http://ipinfo.io/json?callback=JSON_CALLBACK"); }; service.getCurrentWeather = function(city) { var ...

What is the reason for my form data not being saved in the database?

Here is all the code in my app.js file: var express = require("express"); var app = express(); var port = 3000; app.listen(port, () => { console.log("Server listening on port " + port); }); var mongoose = require("mongoos ...

Incorporating conditional Components into Vuejs templates

I have a compilation of various events that are being brought in as logTypes export default { LOGIN: "login", LOGOUT: "logout", } Also, I have two distinct components for each of these occurrences. <LogTypeLogin :item="item ...

Using React Hooks to Implement Checkbox Selection

Having trouble with selecting single or multiple checkboxes in a table using React and Material-UI? Check out my code on CodeSandbox: HERE I'm aiming for a layout similar to the image below: https://i.sstatic.net/dsjGJ.png <TableContainer classN ...

The jQuery mouseout functionality seems to be malfunctioning and not responding as expected

I am currently developing a slider that displays details when the mouse hovers over the logo, and hides the details when the mouse moves away from the parent div. jQuery('.st_inner img').mouseover(function() { jQuery(this).parent().siblings( ...

The art of connecting Javascript commands in succession

I'm struggling to grasp the concept of chaining and return in JavaScript. For example, consider the following code snippet: let array = [1, 2, 3] let newArray = array.map(val => val * 10).map(val => val * 10) console.log(newArray) // [100, 200, ...

Encountering a "Module not found" issue while attempting to utilize the Google APIs Node.js client

Attempting to incorporate the Google API Node.js client into a fresh React Web application. Here is my package.json: { "name": "onboarding", "version": "0.1.0", "private": true, "devDependencies": { "react-scripts": "0.8.4" }, "dependencie ...

Is it possible to transfer the style object from PaperProps to makeStyles in Material UI?

I am working with a Material UI Menu component and attempting to customize its border. Currently, I am only able to achieve this customization by using PaperProps inline on the Menu element. However, I already have a makeStyles object defined. Is there a ...

Performing MySQL queries using PHP and transferring data to JavaScript

UPDATE: I have a number input field with a specific ID attached to it. Within my MySQL database, there exists a table that stores all these IDs along with a list of options separated by commas corresponding to each ID. Let's take one particular reco ...

Pseudo-element fails to display in React when applied to a paragraph tag, even with display block property set

I am experiencing an issue where the pseudo element ::after is not appearing in my browser. I am currently working with React.js and Material UI's makeStyles. Here is the code snippet causing the problem: modalTitle: { borderBottom: '2px sol ...