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

Can someone explain why the console.log(items) command seems to be executing twice

Item.find() .then(function (items) { if (items.length === 0) { Item.insertMany(defaultItems) .then(function () { console.log("Successfully Saved"); }) .catch(function (err) { console.l ...

Can you explain the distinction between export/import and provide/inject in Vue3?

Can you explain the difference between export/import and provide/inject in Vue3? // parent const data = provide('data', ref(0)) // child const data = inject('data') // parent export const data = ref(0) // child import { data } from & ...

Invoke a function from a page that has been reloaded using Ajax

After making an Ajax request to reload a page, I need to trigger a JavaScript function on the main page based on certain database conditions. This is necessary because I require some variables from the main page for the function. PHP code: if($reset_regi ...

How to add a jQuery function to a Rails 3 if statement?

I followed a Rails 3 tutorial on creating a multi-step form which you can check out here. Additionally, I incorporated Stripe payment functionality in my app using another railscast found here. Within my application, the payment form is hidden using jQuer ...

The onclick functionality is not functioning properly within email communications

My JavaScript code contains an AJAX call within Datatables, and this snippet of code is causing an issue: { "data": null, "width": "10%", "render": function(data){ icon2 = '<center><button type="button" class="btn btn-info ...

Compilation failure resulting from core UI build in React js

I have recently transitioned my domain to React Js and am in the process of learning. I have been working on creating an admin panel using Core UI Reactjs components, however I keep encountering an error that says "This error occurred during the build ti ...

Oops! An error occurred while trying to find the _mongodb._tcp.blog-cluster-0hb5z.mongodb.net. Please check your query settings and try again

My free Mongo Atlas cluster suddenly stopped connecting, even though everything was working fine before. Strangely, I can see that data has been collected on the MongoDB website. It's puzzling why this issue occurred and now my entire site won't ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

Utilizing markers for gaming in a data table with Vue and Vuetify

I am struggling to retrieve the games of teams from two objects with arrays in Vue. One object contains headers for a data table, while the other object contains status information. Despite my efforts, I have not been successful in fetching the game detail ...

Mastering the Art of Utilizing $(this) in jQuery

$(".item_listing").hover(function(){ $(".overlay_items").display(); },function(){ $(".overlay_items").hide(); } ); This is my jQuery code. I am trying to display the "overlay_items" div when the "item_listing" div is hovered ov ...

What is the ternary operation syntax for setting the img src attribute in Angular 8?

My data includes a property called "photo" which can either have a file name or be empty. For instance, it could be "steve.jpg" or just an empty string if Steve does not have a photo. In React JSX, I know how to use a ternary operator with the "photo" va ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: How it actually loads: My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component should start with a pre-selected value, which is provided in the c ...

Revamp the website's design

I am looking to revamp the color theme of my website with just a click of a button. Can someone provide me with a link to a reference website where I can get some inspiration? ...

Local host's attempt to retrieve data from an external site via an Axios GET request was rejected

I'm currently attempting to execute a GET request on an external website in order to scrape some information. Unfortunately, my axios GET request is returning a connection error. I suspect that this issue may be related to the fact that I am sending t ...

Create a customized MUI select component with a label, all without the need for assigning an

One issue I am facing is with the Material UI React select component being used multiple times on a page. In the examples, all labeled selects use InputLabel with htmlFor that must match the id of the select. The challenge is that I cannot assign an id t ...

Trigger a JavaScript function when a key is pressed down

Hey everyone, I'm trying to figure out how to trigger a JavaScript function when a particular key is pressed. For example, I want the function down() to be executed when the down key is pressed and function left() when the left key is pressed. Is ther ...

Is there a way to ajax just specific HTML table rows instead of transmitting all the form inputs?

For weeks, I've been struggling to use AJAX POST with a JSP script to update my HTML table rows without success. Can anyone provide guidance on this? Below is what I have attempted so far. window.addEventListener("DOMContentLoaded", function () { ...

Creating a Vue.js component that integrates a Bl.ocks.org graph

I'm a rookie in the world of D3 and I am trying to implement this cool d3 element into my Vue.js component. However, I've encountered an issue with the periodic rotation that I require not functioning properly. It seems to work initially but then ...

How can I link an image source from a JSON file to my template?

Hello, I am new to VueJS and I am encountering an issue. I am trying to connect the IMG src in my template with a URL that is specified in my JSON file. For example, if I have products and I want to display the full logo for each item, I need to link the ...

Is it possible to use jQuery to load content and notify the calling window?

I am implementing the JQuery event "load" to detect when the full HTML window has finished loading along with all scripts being executed. I know this function is typically used within the document.ready event. However, my scenario involves a parent window ...