Updating a boolean value from true to false within a Vue component while making an Axios API request

My Vue.js and Axios setup involves making an API call, where I aim to temporarily change the value of a variable from false to true using SetTimeout. However, there seems to be an issue with Vue not responding unless the variable name is hard coded.

Within my template

<i v-if="fnameEntered" id="fnameCheckPlacement" class="fnameCheck form-control-feedback glyphicon glyphicon-ok" style="margin-right: 10%;"></i> 

And in my script

  methods: {
            submitFirstName: function(event){
                this.updateUserInfo(this.fname, "fname", this.fnameEntered);
            },
            updateUserInfo: function (val, field, checkMark) {
                axios.post('/userprofilepage', {
                    val: val,
                    field: field
                })
                    .then(response => {
                        let self = this;
                        setTimeout(function() {

                            self.checkMark = false;
                        }, 2000);
                        this.checkMark = true;
                    })
                    .catch(error => {
                        console.log(error);
                    })
                    .finally(() => this.loading = false)
            },
        }

I am attempting to pass this.fnameEntered as the checkMark variable into updateUserInfo. When I explicitly set this.fnameEntered = true and this.fnameEntered = false, it works as expected.

However, when trying to use "this.checkMark" or "self.checkMark," nothing happens. What am I missing?

Answer №1

Your update issue may be due to passing a primitive boolean data type in JavaScript, which is always passed by value and not by reference. There are two solutions you can try:

  1. Utilize this.fnameEntered within your method
  2. Transform this.fnameEntered into an object like
    this.fnameEntered = { value: false}
    , then utilize checkMark.value = true within your method

Answer №2

It's unlikely to succeed. Passing this.fnameEntered into the method call means you lose reference to the original property fnameEntered, retaining only a snapshot of its value at the time of invocation. Additionally, both this.checkMark and self.checkMark seek a fixed property name checkMark, distinct from the variable name checkMark.

To access the dynamic property name's value, take these steps:
1. Provide the desired property name as a string.
2. Retrieve the value by using this name.

The process should resemble this:

methods: {
    submitFirstName: function(event){
        this.updateUserInfo(this.fname, "fname", "fnameEntered");
    },
    updateUserInfo: function (val, field, propertyName) {
        axios.post('/userprofilepage', {
            val: val,
            field: field
        })
            .then(response => {
                let self = this;
                setTimeout(function() {

                    self.$data[propertyName] = false;
                }, 2000);
                this.$data[propertyName] = true;
            })
            .catch(error => {
                console.log(error);
            })
            .finally(() => this.loading = false)
    }
}

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 there a way to update the state of App.js based on input from a form submission?

My main React file, App.js, is where I set up my Router and define my routes. I have a route that leads to my Home component and another route that leads to my LoginForm component. Within my LoginForm component, I utilize axios to make a call to an API fo ...

Ways to retrieve a value from a span using the Document Object Model

sample.html <span id='char'>{{value}}</span> sample.ts console.log((<HTMLInputElement>document.getElementById('char'))) This code snippet will display <span id='char'>ThisIsTheValueupdated</sp ...

Using Jquery for a synchronous "Ajax" request doesn't seem to be functioning

As a newcomer to javascript, I am currently in the process of developing a react/flux app and utilizing jquery for synchronous "ajax" calls (sjax?) to the backend. However, I am encountering inconsistent behavior which seems to be caused by my ajax call no ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...

Refreshing a page will disable dark mode

I'm in the process of implementing a dark mode for my website using the code below. However, I've encountered an issue where the dark mode resets when refreshing the page or navigating to a new page. I've heard about a feature called localst ...

Looking to make some changes to the javascript countdown script

Hello, I have come across a JavaScript countdown timer code on stackoverflow that seems to be the perfect solution for my countdown timer project. The current code counts down from 30 minutes to 1 minute and then starts over again. However, it provides the ...

The AutoComplete feature of MaterialUI Component fails to function properly even when there is available data

I am facing an issue with my component as it is not displaying the autosuggestions correctly. Despite having data available and passing it to the component through the suggestions prop while utilizing the Material UI AutoComplete component feature here, I ...

Is JavaScript not having an impact on your HTML code?

I am attempting to create a dynamic number change when the user interacts with the "range-slider" element, but the number is not updating as expected. Below is the code I have written: var rangeSlider = function() { var slider = $(".range-slider"), ...

Use JavaScript to identify and color the intersecting area of two triangles that overlap on a webpage

I created two triangular divs using HTML and I am utilizing jQuery UI to enable them to be draggable. Now, my goal is to overlap these two triangles and change the color of the overlapping area to a different shade. Here is an example: https://i.sstatic. ...

Executing database queries in a synchronous manner in JavaScript

let positionConfig = require('setting'); function retrieveConfig(element) { let setting; positionConfig.find({element: element}, function (err,docs) { console.log(docs[0].current); // show the value setting = docs[0].curr ...

A more intelligent approach for generating JSON responses using Mysql

Here is the code I have on my server side using Node.js: var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'SOMEUSER', password: 'SOMEPASSWD', database: 'SOMED ...

How to import a module from the root path using TypeScript in IntelliJ IDEA

Despite this topic being widely discussed, I still struggle to understand it. Below is my tsconfig.json file: { "compilerOptions": { "module": "commonjs", "target": "es2017", "sourceMap": true, "declaration": true, "allowSyntheticDe ...

Finding the element in the HTML using selenium and Python

Recently, I have been working on automated testing using Selenium. However, I have encountered a strange issue where I am unable to locate the element. Can someone please provide me with guidance on how to handle this situation? driver.find_element_by_xpa ...

Troubleshooting problem with image loading in AngularJS using ng-repeat

Recently delving into using AngularJS in my projects has presented a rather significant issue when utilizing ngRepeat to load thumbnails from a dynamic array into a DIV. While I won't dive deep into the entire application's details here, let me ...

Develop interactive applications with React Native by generating N animated values

Currently, I am in the process of developing a component known as a "Color Palette," which includes a prop called "paletteColors." The "paletteColors" prop is an array with varying lengths that houses color values represented as strings. Within this comp ...

A method to trigger the opening of a div tag when a button is clicked using Vue.js

<div class="input-wrapper"> <div class="mobile-icon"></div> <input class="input-section label-set" type="text" v-model.trim="$v.mobile.$model" :class="{'is-invalid': ...

Invoke functions within a separate function

I am facing an issue when it comes to invoking functions within another function. Below is a snippet of the code I am working with: <script> function saveInfo() { function returnEmail() { var _e = document.getElementById("em ...

A step-by-step guide on simulating a click event on an element in React with the help of jest and react-testing

My component displays the following {list.options && list.options.length > 0 ? ( <div data-testId="MyAlertText" onClick={onAddText}> Add Text </div> ) : null} When testing, I am executing the following it('Ensure Add Text lin ...

What is the best way to dynamically incorporate Before After CSS code in Vue?

I am facing a unique challenge in my current project. I need to dynamically apply colors from data inside a v-for loop, specifically for the :after CSS pseudo-element. While normal CSS properties are easily applicable, I am struggling with applying styles ...

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...