Utilizing Nuxt Axios to assign response data to a variable will dynamically modify the content of the

async fetch() {
    try {
      console.log(await this.$api.events.all(-1, false)); // <-- Logging the first statement
      const response = await this.$api.events.all(-1, false); // <-- Assigning the result
      console.log(response); // <-- Logging the second statement
      if (!this.events) {
        this.events = []
      }
      response.data.forEach((event, index) => {
        const id = event.hashid;
        const existingIndex = this.events.findIndex((other) => {
          return other.hashid = id;
        });
        if (existingIndex == -1) {
          this.events.push(events);
        } else {
          this.events[existingIndex] = event;
        }
      });
      for (var i = this.events.length - 1; i >= 0; --i) {
        const id = this.events[i].hashid
        const wasRemoved =
          response.data.findIndex((event) => {
            return event.hashid == id
          }) == -1
        if (wasRemoved) {
          this.events.splice(i, 1)
        }
      }
      this.$store.commit('cache/updateEventData', {
        updated_at: new Date(Date.now()),
        data: this.events
      });
    } catch (err) {
      console.log(err)
    }
  }

// Other functions that may provide some insights

async function refreshTokenFirstThen(adminApi, func) {
  await adminApi.refreshAsync();
  return func();
}

all(count = -1, description = true) {
  const func = () => {
    return $axios.get(`${baseURL}/admin/event`, {
      'params': {
        'count': count,
        'description': description ? 1 : 0
      },
      'headers': {
        'Authorization': `Bearer ${store.state.admin.token}`
      }
    });
  }
  if (store.getters["admin/isTokenExpired"]) {
      return refreshTokenFirstThen(adminApi, func);
  }
  return func();
},

Two different results are obtained when logging both statements, even though the expected result should be the same. This discrepancy only occurs when using the function in this specific component. In other components, everything works as intended.

First set of data:

[
  {
    "name": "First Name",
    "hashid": "VQW9xg7j",
    // correct attributes
  },
  {
    "name": "Second name",
    "hashid": "zlWvEgxQ",
    // correct attributes
  }
]

The output from the second console.log displays:

[
  {
    "name": "First Name",
    "hashid": "zlWvEgxQ",
    // correct attributes with reactiveGetter and reactiveSetter
    <get hashid()>: reactiveGetter()
​​        length: 0
​​​​        name: "reactiveGetter"
​​​​        prototype: Object { … }
        ​​​​<prototype>: function ()
    ​​​<set hashid()>: reactiveSetter(newVal)
        ​​​​length: 1
        ​​​​name: "reactiveSetter"
        ​​​​prototype: Object { … }
        ​​​​<prototype>: function ()
  },
  {
    "name": "Second name",
    "hashid": "zlWvEgxQ",
    // correct attributes without reactiveGetter and reactiveSetter
  }
]

An unexpected change in the value of the hashid attribute occurs during assignment of the function call response.

Furthermore, the object where the hashid field changes also receives reactiveGetter and reactiveSetter, unlike the second object in the array.

This behavior raises questions about the nature of the assignment operations or a potential interaction with Vuex store. When using the same function elsewhere, the Vuex store remains unaffected.

The backend consistently provides accurate data, consisting of an array with two objects and specific attributes. No additional data is anticipated beyond these two objects.

If anyone can shed light on why this irregular behavior is observed, it would greatly help to understand the underlying cause.

Answer №1

There are a couple of issues...

  1. Avoid using console.log with objects because browsers may display a "live view" of the object - check this reference

  2. The statement

    this.events.findIndex((other) => { return other.hashid = id; });
    is incorrect as you are using an assignment operator (=) instead of the identity operator (===). This results in the hashid attribute of the first element being modified...

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

Two Vue.js components accessing shared data retrieved from a service call

Currently, I am working with two Vue components. The first component is connected to the Data Store in order to retrieve the necessary data for binding. This component is responsible for displaying multiple details (records). The second component also requ ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

I am looking to showcase images beside individuals' names or photos on my website in a vertical arrangement, similar to how it is done on Facebook

Looking for suggestions on how to display images uploaded by users on my webpage in a way similar to Facebook, with the user's photo displayed beside each image. Any recommendations or website links would be greatly appreciated. Thanks, Santosh Sahu ...

Prevent the bottom row from being sorted

I have implemented sortable table rows in my angular project, however the sorting functionality also affects some query-ui code elements. Now I am looking to exclude the last row from being sortable. HTML <div ng:controller="controller"> <ta ...

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

Show the JSON data returned

Looking for a way to display the JSON response in a JSP page using AJAX... function doAjaxPost() { var name = $('#name').val(); var password = $('#password').val(); var gender = $('#gender').val(); var abo ...

Show the total of a JavaScript calculation in a designated input box

Is there a way to show the total sum of this calculation in an input field? function calculateSum1() { var sum = 0; //loop through each textbox and add their values $("input.miles").each(function() { //only add if the value is a number ...

Upon clicking a button, initiate an Ajax call to retrieve a value from the code behind (aspx.cs) and display it in an input field on the same page

I am a beginner in the world of AJAX and encountering a problem. I need to initiate an AJAX call when a button is clicked. The goal is to send the value of an input field to the code behind page, aspx.cs, and then display the response from that same input ...

Vuetify - Best practices for vertically aligning rows in a v-treeview component

Just getting started with Vue js, so pardon me if this is a silly question. I've scoured the internet and can't seem to find a solution. I'm working on a v-treeview displaying a folder structure, with descriptions of each folder in a separa ...

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...

Tips on organizing and designing buttons within a canvas

let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.style.background="yellow" canvas.wid ...

Performing an AJAX request to validate a username when it loses

Hey everyone, I'm currently working on a script that checks the availability of a username in a MySQL database using an onblur event with AJAX. Here's the AJAX script: document.getElementById("r_username").onblur = function(){ var http ...

The 'authorization' property is not available on the 'Request' object

Here is a code snippet to consider: setContext(async (req, { headers }) => { const token = await getToken(config.resources.gatewayApi.scopes) const completeHeader = { headers: { ...headers, authorization: token ...

Electron triggers MouseLeave event on child elements

Dealing with mouse hover events can be a bit tricky, especially when working with AngularJS in an Electron-hosted app. Here's the HTML template and script I'm using: HTML: <div id="controlArea" (mouseenter) = "onControlAreaEnter()" ...

In what way can the button display the permission directly on the page?

When the website notification is granted, a green button should be displayed. If it is denied, show a red button instead. The button comes with a CSS style and a checkbox but does not have the permission to grant or allow any permissions on the page. Butt ...

Having trouble using the `.not` function in jQuery

I'm working on implementing a collapsible menu using jQuery. When any header is clicked, the next sibling (the box) should expand while all other boxes collapse. HTML <div class="finbox" id="finbox1"> <div class="finheader" id="finheade ...

Hiding the icon if there are no child elements present

Currently, I am in the process of constructing a TreeView using the Treeview component from Material UI, which can be found at this link. The component I have designed below is responsible for fetching data when a node is expanded. The tree structure is s ...

Is there a way to retrieve the request object within loopback operational hooks?

I am currently utilizing loopback 3.x and have created an Access Hook within my code. My goal is to include a condition based on the User Agent. Specifically, I am looking to access Request > Headers > User-Agent. Is it feasible to retrieve this in ...

When using jQuery AJAX to Like/Dislike, a 500 (Internal Server Error) is returned, but the functionality works correctly upon reloading the

My website has a feature where users can press a Like Status button that uses AJAX to send data to the controller. When the button is clicked, it changes from "like" to "dislike" and all associated classes and form actions are updated accordingly. The is ...

How to access a custom filter in ng-repeat using AngularJS

I'm working on creating a filter to sort through the items displayed in a table. Specifically, I want to filter out items based on a certain property value that may change depending on user input. I have attempted the following approach and it seems t ...