It seems that the JavaScript object is producing varied values in distinct locations despite no alterations made in between

I've encountered a puzzling issue where a variable is returning different values within a function, despite no modifications being made to it.

This problem arises in a form component created using Vue.js (v2) that triggers a Vuex action. While I believe this isn't directly related to Vue/Vuex, understanding the code snippet is crucial.

Below is the relevant code excerpt from my component:

import { mapActions } from 'vuex'

export default {

  data() {
    return {
      product: {
        code: '',
        description: '',
        type: '',
        productImage: [], 
        productDocs: {},
      }
    }
  },

  methods {

    ...mapActions(['event']),

    save() {
      console.log("this.product:", this.product)
      const valid = this.$refs.form.validate()
      console.log("this.product:", this.product)
      if (valid) {
        try {
          this.event({
            action: 'product/addProduct',
            data: this.product
          })
        }
        finally {
          this.close()  
        }
      }
    },

// more code

Here's a snippet of the vuex action "event":

event: async ({ dispatch }, event) => {
      const time = new Date()
      const evid = `${Date.now()}|${Math.floor(Math.random()*1000)}`
      console.log(`Preparing to dispatch... Action: ${event.action} | data: ${JSON.stringify(event.data)} | Event ID: ${evid}`)

      // enriching event
      event.evid = evid;
      event.timestamp = time;
      event.synced = 0

      // Push user event to buffer
      try {
        await buffer.events.add(event)

      } catch (e) {
        console.log(`Error writing event into buffer. Action ${event.action} | evid: ${evid} `)
      }

      // dispatch action 
      try {
        await dispatch(event.action, event)
      }
      catch (err) {
        console.log(`Error dispatching action: ${event.action} | data: ${event.data}\n${err.stack || err}`)
        window.alert('Could not save. Try again. \n' + err + `\n Action: ${event.action} | data: ${event.data}`)
      }
    },

The issue revolves around this.product. Despite placing multiple console.log statements to inspect the values, the logs from the save() function show as undefined, while the event function (a vuex action) displays the expected values as depicted in the console outputs:

When this.product is logged in the save() function, both instances yield the same result.

Contrastingly, logging the event in the vuex action reveals that event.data corresponds to the product.

I'm evidently missing something critical here, but I'm unable to pinpoint it. Any assistance would be highly appreciated.

Answer №1

@Sumurai8: Your edits to the question and your hint were greatly appreciated.

One interesting observation I made was the small "i" next to the opened product. Upon hovering over it, a message stating that "the object has been evaluated just now" appears. This suggests that the evaluation occurs when the object is opened, which happens after the action is executed. It's possible that any changes to the product occur after this event.

Your insight actually led me to discover the solution.

Essentially, within the this.close function called in the finally statement of the save() function, I inadvertently reset the form along with this.product, which solely held the form data. As a result, at evaluation time, the object contained undefined properties. The event function managed to output to the console before the reset, but the store wouldn't update as expected (this discrepancy alerted me to the issue). This disparity occurred because the event function and the action it called were asynchronous, causing the value to be reset prior to the actual mutation of the vuex store.

Upon logging JSON.stringify(this.product), I confirmed that the correct value was being output within the save() method. With this information, I created a more robust copy of the data and passed it to the event function like this:

this.event({
  action: 'product/addProduct',
  data: JSON.parse(JSON.stringify(this.product))
})

With these adjustments, everything now functions seamlessly.

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

What is the best way to format table values as currency?

Still getting the hang of Javascript, and I'm in the process of learning... Currently, my challenge involves calculating the total sum of values within a Bootstrap 4 table and formatting the result as currency (specifically in USD format). While I&ap ...

Creating input fields dynamically within Yii2 framework

I'm currently facing a challenge with forms in Yii2. My objective is to design a form that includes three dropdown menus, inquiring about the user's preferred time(s) during the week. The first menu will focus on selecting days of the week, while ...

Ways to pass scope between the same controller multiple times

There is a unique scenario in which I have a controller appearing in 2 different locations on a page. This arrangement is necessary for specific reasons. To illustrate, the simplified HTML structure is as follows: <aside ng-if="aside.on" ng-controller ...

What is the technical process behind conducting A/B testing at Optimizely?

I'm currently experimenting with Google Analytics and Content Experiments for A/B testing on my website, but I'm encountering some challenges in making it seamless. To utilize the Google API properly, a few steps need to be taken. Firstly, I nee ...

Component not refreshing when state changes occur

I have a unique react application that resembles the one showcased in this codesandbox link https://codesandbox.io/s/eatery-v1691 By clicking on the Menu located at the bottom center of the page, it triggers the display of the MenuFilter component. The M ...

How can I efficiently extract specific data from JSON using AngularJs?

In my array (_users), there are JSON objects. { "User": { "userid":"19571", "status":"7", "active":"1", "lastlogin":"1339759025307", "Stats": [ { "active":"1", "catid":"10918", "typeid":"71", ...

Error: Scheme is not a valid function call

Currently, I am attempting to implement user registration functionality in a Node.js application using MongoDB. However, I encountered this error: var UtenteSchema = Scheme({ TypeError: Scheme is not a function Below is my model utente.js: cons ...

Exploring the capabilities of Google Drive API using Requests library

I am interested in streaming a file from a remote source to Google Drive. By utilizing the request library, you can easily download files locally like so: request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png') ...

Text parsing with jQuery

Hello fellow developers. I am interested in creating a text parser using jQuery. My goal is to develop a function that can take a string as input and convert it accordingly. Imagine we have a div with the following HTML structure: <div class="item"> ...

Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggest ...

Having trouble running the npm development server

The command npm run dev was executed. This ran the scripts concurrently using "npm run server" and "npm run client". Error from npm: Missing script: servernpm npm error. Did you mean this? Should it be: npm run server # to run the "server" package script ...

Ways to pause JavaScript execution until a function completes its task

Is it possible to pause JavaScript execution until a specific function finishes in JavaScript/NodeJS? For instance: https://i.stack.imgur.com/Ta8pj.png Imagine the first line of code triggers an alert, and JavaScript stops executing until the user interac ...

Unable to display shadows in Three.js

I've hit a roadblock with the shadow effect at the moment, despite trying various solutions for hours, it's still not appearing. Can anyone point out what I may have done incorrectly? Below is the code snippet for my current scene: //Setting up ...

NodeJS making seven successful Ajax requests

I'm delving into the world of JavaScript, NodeJS, and electron with a goal to create a presenter-app for remote control over powerpoint presentations. My setup involves an electron server structured like this: const electron = require('electron ...

Setting up vue-resource root and authentication configuration

Currently, I am reviewing the documentation for vue-resource that outlines how to configure it: https://github.com/vuejs/vue-resource/blob/master/docs/config.md The documentation specifies setting headers with a common authorization value: Vue.http.hea ...

Ways to create a group label to modify various textboxes when a click event occurs

Is it possible to change multiple textboxes with corresponding labels after a click event? Issue: The current output only displays the value of the last textbox. $(function () { $('a.edit').on('click', function (e) { e.pre ...

Extracting the CSS styles utilized by individual components in a Vue project

Description In my Vue 2 project, I have integrated bootstrap and an additional UI kit. However, customizing the CSS of my components has proven to be a challenge due to the complex abstractions present in the UI kit's variables. Looking For I am ...

Effortlessly eliminate query strings from a URL in a Vue SPA application

Imagine you have a Vue2 application at http://www.example.com, with two routes ('/', '/dashboard'). When someone accesses '/', they are automatically redirected to '/dashboard'. Now, another single sign-on (SSO) s ...

Trouble displaying JSON data when using a search box filter in React

My webpage is using JSON dummy data that can be filtered by keywords entered into a search box. Previously, all the data displayed correctly before creating filteredJson, but now nothing is showing up. What could be causing this issue? I want to send the ...

Transforming the appearance of the menu element in Vue using transitions

In my Vue app, I have this SCSS code that I'm using to create a smooth transition effect from the left for a menu when the isVisible property is set to true. However, I am encountering an issue where the transition defined does not apply and the menu ...