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

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Whenever I try to run npm start, my webpack is not able to locate my index.html page

Recently delving into the world of node.js and its packages, I initiated by executing npm init to lay out the package.json structure shown below: { "name": "test", "version": "1.0.0", "description": & ...

What method does jQuery Validation use to configure the validation message?

A custom method was developed for the jQuery validation plugin to validate whether a given value meets the length requirements set during validation. The method is structured as follows: jQuery.validator.addMethod("exactLength", function(value, ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...

Avoiding memory leaks in Node.js with Express framework

Dealing with memory leaks in nodejs (express.js) has been a challenge for me. I followed various tutorials online, but unlike the examples provided, identifying the source of the leak in my code has not been straightforward. Through the use of Chrome Dev T ...

Discovering the process of previewing a video upload using react-player

Currently, I have an input that allows users to upload video files of type File. In my application, there is also a react-player component that requires a URL prop, which can be either an array or MediaStream according to its documentation. After doing som ...

Issue with CSS loading in production with Vue and webpack

Currently, I am utilizing webpack within a Vue+Rails project. The issue arises when operating in development mode as all CSS functions properly. However, in production mode, the CSS fails to load, as depicted in the image below: https://i.stack.imgur.com ...

Does the triple equal operator in JavaScript first compare the type of the value?

When using the triple equal operator, it not only measures the value but also the type. I am curious about the order in which it compares the value and returns false if they do not match, or vice versa. ...

Communication between the front-end (react) and backend (nodejs) is unable to retrieve only the specific value via API call

As a newcomer to backend/frontend development, I'm facing an issue that I can't seem to resolve... I have a store.js file that stores user interaction data (using zustand). One of the variables, 'feed', returns a value like "0xD4a3386 ...

Understanding the process of verifying signatures with Cloud KMS

I've been struggling to confirm the validity of a signature generated using Google's cloud KMS, as I'm consistently receiving invalid responses. Here's my approach to testing it: const versionName = client.cryptoKeyVersionPath( p ...

Should WordPress files be kept separate (php, css, and js) or combined into a single file?

Currently, I am updating my WordPress website with a goal of minimizing the number of plugins used. To achieve this, I prefer writing code only for essential functionalities. In order to optimize my work with php, css, and javascript files, I have been exp ...

Avoid triggering the pointerenter event when touching and subsequently moving into an element

I am currently working on a React application where I want to enable a user to touch one element and then move to an adjacent element while keeping the touch continuous. The issue I am facing is that the pointerover and pointerenter events only trigger whe ...

How to delete a line from a file in Node.js without modifying the buffer variable

Hello everyone, I am just starting to explore the world of Nodejs Recently, I created a function that reads data from a file, saves it in an array variable, and then makes some changes to this variable before writing it back to the file. The code snippet ...

Passing JSON data with special characters like the @ symbol to props in React can be achieved

Using axios in React, I am fetching JSON data from a database. I have successfully retrieved the JSON data and stored it in state to pass as props to child components within my application. However, the issue arises when some of the objects in the JSON s ...

Removing a specific MySQL row using HTML in collaboration with Node.js

I've been working on a feature to allow users to delete specific rows from a table. Each row has a "Delete" link at the end, but when I click it, nothing happens. There are no errors displayed, and the console shows that 0 row(s) have been updated, ye ...

Loss of image quality when utilizing Next/Image in NEXT JS

I am currently developing a web application using Next.js 13, and I recently noticed a decrease in the quality of my images. I'm not sure what went wrong or what I may have missed. Upon inspecting the HTML element on the browser, I found this code: & ...

Troubleshooting: Difficulty Reading .val() on Elements Selected by Class in jQuery.fn.init(9)

I am facing an issue while trying to retrieve all elements with a specific class name using the code below: productPrices = $('.product-price'); Instead of getting individual values, I am getting the following output: jQuery.fn.init(9) [div. ...

Error: Attempting to access the property 'push' of an undefined variable has resulted in an unhandled TypeError

if (Math.random() <= .1) { let orgAdmin = User.find({email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1234454665324721380c0d">[email protected]</a>'}); or ...

Generate clickable links on a web page with PHP and a form

Every week I find myself tediously creating links by manually copying and pasting. It's starting to feel like a crazy process, and I'm sure there must be a faster way. A123456 B34567 d928333 s121233 I need these numbers to be transformed into h ...

Swapping out data points using JQuery

What could be causing line 10 to return null? Click here for the code file The code seems to function properly with line 40, but not with line 10. ...