Issue with Vue: Radio buttons fail to update their value when data changes in an asynchronous manner

I'm having trouble with my new code and I can't figure out why it's not working properly. I created a minimum reproducible case to showcase the issue. Interestingly, when the data is set synchronously in the `created()` hook, everything works fine and the article radio button is displayed correctly. However, when I enclose it in a timeout function, the blog option remains selected instead of the article. I am using Vue version 2.6.12.

Although the bug in this particular code has been resolved, it wasn't the root cause of my actual problem since my real code differs from this example. The main issue I'm facing is that the radio button doesn't get checked as expected after the reactive data changes.

<Radio
  v-model="type"
  identifier="article"
  class="pl-3"
  label="article"
  name="type"
/>
<Radio
  v-model="type"
  identifier="blog"
  class="pl-3"
  label="blog"
  name="type"
/>
<div>Selected {{ type }}</div>

  data() {
    return {
      type: "blog",
    };
  },
  created() {
    setTimeout(function () {
      this.type = "article";
      console.log(this.type);
    }, 800);
  },

This scenario is frustrating because a similar piece of code in a different component functions correctly.

UPDATE:

The original code causing issues looks like this:

computed: {
  blog() {
    return this.$store.getters.BLOG;
  },
},
watch: {
 blog() {
  this.type = (this.blog.info.editorial) ? 'article' : 'blog';
 },

created() {
  this.$store.dispatch('FETCH_BLOG', { slug: this.slug });
},

Links to relevant source code:

Answer №1

Simply update your function to an arrow function as it is not referencing your data correctly

setTimeout(() => {
      this.type = "article";
      console.log(this.type);
}, 800);

Answer №2

The issue lies in the fact that the selected property within the Radio.vue component is only assigned the value of value in the created() hook. When a setTimeout() function is triggered in the parent component, it changes the v-model property of Radio.vue, which updates its value property. However, the selected property is not automatically synchronized to this change.

To resolve this issue, you can replace the assignment in the created() hook with a watcher on the value property that updates the selected property:

// Radio.vue
export default {
  created() {
    // ⛔️ Remove this
    //if (this.value) {
    //  this.selected = this.value
    //}
  },

  watch: {
    value: {
      handler(value) {
        this.selected = value
      },
      immediate: true,
    },
  },
}

demo

Answer №3

It seems like your original code doesn't include setting the type in Vue's data function, which means it won't be reactive when you assign a new value to this.type.

Dealing with state management in forms can be tricky, but have you checked out this library: https://github.com/vue-formily/formily? It might make working with forms easier for you by letting you separate form definitions from Vue components, making them reusable, and automatically managing the state.

For a demo related to your issue, you can take a look at this sample: https://codepen.io/hqnan/pen/YzQbxxo

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

AngularJS - Using filters to extract specific options from multiple <select> components

There are N "select" components generated based on JSON data, with the "options" populated by an external API. I am trying to implement a custom filter that ensures when an option is selected in one "select" component, it should not appear in the other com ...

Identify when JavaScript makes calls to C# methods

My team and I are currently working on a .NET MVC project in Visual Studio, where we frequently need to invoke controller or model functions from JavaScript files. An example of this is: $.ajax({ "dataType": 'json', ...

Obtaining access to an element using jQuery AJAX in MVC

When using jQuery ajax to send data to an action, I want to display the returned data in a table. The action method returns an object in Json format: public JsonResult CountryList(.....) { CountryTypeViewModel obj = new CountryTypeViewModel(); . ...

Leveraging Angular Dragula without the need for RequireJS

I'm eager to incorporate Drag and Drop functionality into my Angular project with the help of the angular-dragula module (https://github.com/bevacqua/angular-dragula). However, it appears that this module heavily relies on RequireJS. My experience wit ...

Switching images using a button in VueJS

/* Defining reactive variables */ const question = ref(false) const changeQuestion = ref(false) /* Computing the image to display based on the boolean value of changeQuestion */ const changeQuestionButton = computed(() => { if (!changeQuestion.value) ...

Controlling Fabric in Three.JS

(I'm still learning so forgive me if this is a beginner question.) I'm currently working on fitting a cloth material to a character model in Three.JS. What would be the most effective approach for this? Should I create a complete garment as cloth ...

Unable to retrieve attributes from the object

Encountering a strange issue that has left me stumped. What I'm trying to do is parse a CSV file into a JSON object and store it in my redux store. The parsing process seems to be working fine, with everything compiling neatly into a JSON object withi ...

When multiple checkboxes are selected, corresponding form fields should dynamically appear based on the checkboxes selected. I attempted to achieve this functionality using the select option method

Require checkboxes instead of a selection option and have multiple checkbox options. Depending on the checked checkboxes, different form fields should appear. A submit button is needed. I have included some CSS code, but a more detailed CSS code is requir ...

Delineate parameters and the various endpoints of an API

Having multiple express API endpoints serving different purposes, I am facing an issue where a single endpoint is returning results for all requests. For instance, the "api/:id" endpoint should return the id, while the "api/:id?region=east" endpoint should ...

"Troubleshooting: Vue JS Axios Post Request Not Passing Data to PHP Server

After successfully uploading an image in Vue JS and sending a POST request to a Laravel Route, the JSON response from the API is displayed on the client side as expected. However, there seems to be an issue with retrieving this response in PHP, as it retur ...

Tips for crafting effective error messages to communicate with users

One of the biggest challenges I face is crafting clear error messages for clients in case of errors. A typical scenario involves using Axios and a third-party API to fetch data, requiring appropriate error handling for both. Axios' error handling doc ...

Exploring the world of HTML5 speed testing: getting started

Can anyone provide guidance on how to begin with an HTML5 bandwidth test? I am trying to replicate a flash-based version and any recommendations would be greatly appreciated. ...

The initialization of Firebase is not being completed before it is being called in other files

I am currently working on a vue project and I am attempting to integrate firebase. However, I have encountered an issue where my other JavaScript files like auth.js are utilizing firebase before it is properly initialized in my main.js file (which acts as ...

Storing information in Vue.js across page redirects

I need assistance with maintaining my Vue.js application data while redirecting to an external credit card payment page and then back to my app. How can I ensure that my app data is preserved during these redirects, especially considering the large amoun ...

Creating a custom datepicker in Vuetify with validation

I'm in the process of developing a new component that consists solely of a datepicker with validation capabilities. This component is designed to be versatile so that it can be easily integrated into multiple components. My goal is to display a red va ...

Angular view displaying dropdown selection value

I find myself in a unique situation. I have implemented a dropdown called caseStatus within an ng-repeat loop, connected to a model containing Case Statuses. While this setup works fine and multiple dropdowns are rendered on the page as expected, there is ...

Using Selenium Webdriver to open a JavaScript calendar popup window

While testing a basic website, I encountered an issue with the Firefox webdriver not displaying a Javascript calendar window when a button is clicked. Even though the Selenium IDE successfully spawns the window, running the Java code does not result in the ...

The JSON response is returning an undefined value

While working on my react app, I am logging JSON data from the backend of the application. When I log the main body of the data: console.log('........section2', options2ndSection[2]); The returned JSON data is as follows: Object item: ...

Utilizing Google Charts to Generate Dynamic Arrays in PHP Without the Need for

I'm facing this issue because most of the solutions I found online are based on MySQL, but I am using a JSON API to retrieve data and then converting it into arrays for displaying in a Google graph. I know that I need to format the arrays correctly to ...

How is it possible to enter the letter "e" when the input is supposed to be a number?

While typing, I mistakenly entered the letter "e" and it ended up being recorded in the input field. <input type="number" v-model="value"/> Strangely, other letters do not seem to be recorded in the same way. https://i.sstatic.n ...