How to return the same value as the input value in Vue before the action is completed

When creating a component and module for functionality X while using Vuex for state management, the code initially works fine. However, after the first insertion, the Getter function consistently returns the previous input value before the action is committed to mutation.

For instance:
1 - All values are [0,0,0] with the Getter also being [0,0,0]. Upon inserting a 9 in the first position, the value gets inserted.
2 - On subsequent tries, the check to see if the inserted value matches the state always evaluates to true, leading to the need to remove this verification step.

Interestingly, even though the state continues to change without committing those changes to the mutation, querying the Getter (which retrieves the state's value) already reflects the newly inserted value.

Anyone have suggestions on how to resolve this issue?

Here is the revised code snippet:

Component:

Vue.component('profundidade-cell', {

    data: function () {
        return {
            valorProfundidade: [0, 0, 0],
            id: this.face + '-' + this.dente,
            ids: [
                this.face + '-profundidade-sondagem-' + this.dente + '-1',
                this.face + '-profundidade-sondagem-' + this.dente + '-2',
                this.face + '-profundidade-sondagem-' + this.dente + '-3'
            ],
            changedId: null,
            valorInserido: null,
            valorAnt: null,
        }
    },

    props: {
        arcada: String,
        sextante: String,
        dente: String,
        face: String,
        face_json: String,
        max_length: Number,
        min_value: Number,
        max_value: Number,
    },

    computed: {
        profundidadeSondagem() {
            return store.getters['profundidadeSondagem/profundidadeSondagem']({arcada: this.arcada,
                sextante: this.sextante, dente: "dente_" + this.dente, face: this.face_json});
        },

        presente() {
            return store.getters.dentePresente({arcada: this.arcada, sextante: this.sextante,
                dente: "dente_" + this.dente});
        }

    },

    created: function() {
        this.debouncedAlterarProfundidade = _.debounce(this.alterarValorProfundidadeSondagem, 400);
        this.$root.$on("vuex-carregado", this.carregar);
    },

    methods: {

        getValue(e) {
            this.changedId = e.target.id;
            this.valorInserido = e.target.value;

            this.debouncedAlterarProfundidade();


        },

        alterarValorProfundidadeSondagem() {

            let modelRefs = {};

            let patologia = {
                arcada: this.arcada,
                sextante: this.sextante,
                dente: "dente_" + this.dente,
                face: this.face_json,
                valor: this.valorProfundidade,
                modelRefs: modelRefs,
                id: this.changedId,
                valorInserido: this.valorInserido,
            };

            store.dispatch('profundidadeSondagem/MODIFY', patologia).catch(() => {

                this.valorProfundidade = this.profundidadeSondagem;
            })

        },

        carregar(){
            this.valorProfundidade = this.profundidadeSondagem;
        }

    },


    template: `
        <div>
            <input type="text" :id=ids[0] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[0] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />
            <input type="text" :id=ids[1] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[1] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />
            <input type="text" :id=ids[2] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[2] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />    
        </div>
    `

});

Module:

const moduleProfundidadeSondagem = {
    namespaced: true,

    actions: {
        MODIFY({commit, dispatch, getters, rootGetters}, obj) {
            let patologia = {
                face: rootGetters.getNomeFace(obj.face),
                dente: rootGetters.getNomeDente(obj.dente),
                local: "FACE",
                ficha: this.state.idPeriograma,
                descricao: obj.valor.toString(),
                paciente: this.state.idPaciente,
                tipo: 'PROFUNDIDADE_DE_SONDAGEM'
            };

            if(store.getters.profundidadeSondagem !== obj.valor) {

                let reg = new RegExp(/([0-9],[0-9],[0-9])/);

                let param = null;

                return new Promise((resolve, reject) => {
                    if(obj.valor[0] == 0 && obj.valor[1] == 0 && obj.valor[2] == 0) {
                        param = axios.delete('/patologia', {data: patologia});
                    } else if (reg.test(obj.valor)){
                        param = axios.post('/patologia', patologia);
                    }

                    if(param != null) {
                        param.then(function (response) {
                            if(response.status == 200 || response.status == 201 && response.data) {
                                commit('armazenarProfundidadeSondagem', obj);

                                let dentes_data = {};
                                let face = '';

                                if (obj.arcada == 'arcada_superior' && obj.face == 'face_lingual_palatal') {
                                    face = 'palatina';
                                } else {
                                    face = obj.face.split('_')[1];
                                }

                                let classe_canvas = rootGetters.getNomeClasseCanvas(obj, face);

                                drawGraph(rootGetters.prepareDentesData(obj, face, dentes_data), face,
                                    classe_canvas);
                                resolve();
                            }

                        }).catch(error => {

                            store.dispatch('mensagemAlerta/ALERTA', {
                                tipo: 'error',
                                mensagem: 'Não foi possível cadastrar o nível de sondagem'
                            });

                            reject(error);
                        });
                    }
                })
            }
        },

        RESET_PROFUNDIDADE_SONDAGEM({commit}, ob) {
            commit('RESET_ALL', ob);
        }
    },

    getters: {
        profundidadeSondagem: (state, getters, rootState) => obj => {
            return rootState[obj.arcada][obj.sextante][obj.dente][obj.face].profundidade_sondagem;
        }
    },


Answer №1

It seems like the main issue is here:


TL;DR - you are passing your getter as a value to your action.


This is just a guess, as I am unable to debug your code


        store.dispatch('profundidadeSondagem/MODIFY', patologia).catch(() => {

            this.valorProfundidade = this.profundidadeSondagem;
        })

By assigning a reference from your rootState[...], you end up altering the properties of the rootState[...] in your component after the initial run.

Therefore, your code starts behaving like this:

        let patologia = {
            arcada: this.arcada,
            sextante: this.sextante,
            dente: "dente_" + this.dente,
            face: this.face_json,
            
          // valor: this.valorProfundidade,
          ///* same as */ valor: this.profundidadeSondagem,
          /* same as */ valor: this.$store.getters['profundidadeSondagem/profundidadeSondagem'](...),
            modelRefs: modelRefs,
            id: this.changedId,
            valorInserido: this.valorInserido,
        };

To address this issue, consider using

this.valorProfundidade = this.profundidadeSondagem.slice();
if it is an array or Object.assign({},...) to prevent references.

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

Why does Request-Body(req.body) display a value while Request-QueryParams(req.queryParams) returns null?

Using vuejs-axios, I successfully transferred client-side data to the server-side using Java with SparkJAVA Framework to manage the request-response cycle. The following code snippets demonstrate how Form-Data is posted from vuejs to java. const formData ...

Sending a POST request to a PHP file in React: A Step-by-Step Guide

Just starting out with reactjs and trying to figure out how to send an ajax request to a server (php file). Here's the structure of my project: check it out here src/index.js import React from 'react'; import ReactDOM from 'react-dom& ...

Distribution running of VueJS doesn't show styles

Even though I am able to successfully run my Vuejs app using nom run serve, I am facing an issue when I build it and deploy it to nginx. None of my styles, especially bootstrap, are appearing. Despite my app logic appearing correct and all my js and css ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...

Using data binding in VueJS to construct a dynamic URL

Exploring VueJS for the first time and it's been a great experience so far. However, I'm facing a couple of challenges with data binding. The requirement is for the customer to input an image URL, and no image should be displayed until a valid ...

Click on the div to automatically insert its text into the textarea

I am looking for a way to enable users to edit their posts easily. My idea is to have them click on a link, which will then hide the original div containing their post and reveal a new div with the old text inside a textarea for editing. Despite searching ...

Utilize custom fonts from your local directory within a Vite Vue3 project

Inside my main.scss file, I am loading local fonts from the assets/styles/fonts folder: @font-face { font-family: 'Opensans-Bold'; font-style: normal; src: local('Opensans-Bold'), url(./fonts/OpenSans-Bold.ttf) format('truety ...

Is my Laravel application experiencing caching issues preventing real-time updates?

As I dive into learning AngularJS, I've encountered a strange issue where changes made in my JS files don't always seem to take effect. Even after seeing the GET request to the file in the console, the content remains unchanged. I can delete all ...

Encountering null injector errors when running ng test on an Angular application

I have successfully developed a webpage in my Angular application and it is running perfectly. But, when I run ng test, some errors are popping up in Karma like the one shown in the image below: https://i.sstatic.net/lUKS5.png superuser.component.ts // ...

Troubleshooting Event.target Problem in Firefox 6

When working in Firefox 6, I encountered an issue while trying to identify the target element on which the event occurred. Instead of displaying the desired element, it was showing as undefined in the alert message. Utilizing the Firebug tool for debugging ...

Obtaining the domain from a cookie using AngularJS

I've encountered a issue with removing cookies from my browser when logging out. It seems that I need to specify the domain in order to remove them correctly. $cookies.remove('Name',{domain:'.test123.com'}); My goal is to automat ...

Leverage the variable from one function in a different function within Three.js using Javascript

After loading an obj file using three.js, I attempted to obtain the 'X' position of its vertices and save it in a variable named 'pos' inside the objloader function within the init() function. My goal was to access this variable's ...

The issue of CSS not being applied to HTML content after being inserted via AJAX has been encountered

I've successfully implemented AJAX to retrieve specific page content from a database, but now I'm facing an issue: When it comes to the 'Contact' page, the form retrieved from the database (as HTML) is not applying the CSS styles I hav ...

TinyMCE - The control with the name 'content' is considered invalid and cannot receive focus

I am utilizing TinyMCE 4 and here is the code snippet for it: <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script> tinymce.init({ selector: 'textarea[name=content]', ...

unexpected alteration of text sizing in mathjax within reveal.js presentations

Something strange is happening with the font size in my slides. The code for each slide is the same, but there is an unexpected change between the 3rd and 4th slide. I cannot figure out what is causing this discrepancy. Oddly enough, when I remove the tit ...

Is there a way to lead to a password-protected page without making it accessible through the URL?

I'm currently honing my skills in web development and embarking on a project to create an interactive puzzle website. The premise is simple - the homepage will feature just an answer input field where users can enter the correct solution to progress t ...

Issue encountered with invoking carousel.to() method in Bootstrap 5

// Create a new carousel instance let car = new bootstrap.Carousel(document.querySelector('#carouselMenu'), { interval: 0, wrap: false }); // <SNIP> // Go to page at index 1 car.to("1"); Error: https://i.sstat ...

Ensure every individual input field in a Bootstrap form is validated using JavaScript before submitting the form

As a newcomer to Javascript, I am seeking assistance with validating each field in the form below without having to click on the submit button. Your help is greatly appreciated! <form action="" id = "form1" class = "form-group row"> & ...

Maintain the state of the previous page in Vue to ensure continuity

Currently in the process of creating a small PWA to simulate an Android app, I have discovered Vuejs. However, I encountered an issue that has proven difficult to resolve. While scrolling through lists on the homepage for movies, TV shows, or news, clicki ...

What is the process for altering an SVG image following a click event in Javascript?

I have a tab within a div that includes text and an svg icon as shown herehttps://i.stack.imgur.com/TjwIK.png When I click on the tab, it expands like this https://i.stack.imgur.com/XNuBi.png After expanding, I want the svg icon to change to something e ...