The Vue Application has encountered a persistent loop caused by interdependent variables, presenting a challenging logic problem

I have been developing a Vue application that allows users to convert between fiat currency and cryptocurrencies. You can try the app out for yourself here: Demo.

One interesting feature of the app is that the conversion calculation happens automatically in real-time as you type, displaying the result in the other input box. However, I've encountered an issue where the calculation only occurs when changes are made to the input variables.

In addition to updating on user input, I also want the calculation to happen when a different option is selected from the dropdown menu.

I've been struggling to find a solution without creating an endless loop in the process.

My initial attempt to solve the problem can be found here: codepen.

From my understanding, the current issue arises because:

...input1 changes -> watch input1 called -> watch input1 modifies 
input2 -> watch input2 called -> watch input2 modifies input1....

This creates an infinite loop situation. It seems there's a specific aspect of Vue.js that I haven't mastered yet to address this particular challenge.

Thank you for your help,

Answer №1

To achieve synchronization between two input fields, utilize the @input event listener. This means that when you modify the value in one input field, it will automatically update the value in the other input field.

<template>
  <div>
    <input v-model="value1" @input="update2"> 
    to 
    <input v-model="value2" @input="update1">
  </div>
</template>

<script>
const mul = 1.5;
export default {
  data: () => ({
    value1: null,
    value2: null
  }),
  methods: {
    update1() {
      this.value1 = this.value2 / mul;
    },
    update2() {
      this.value2 = this.value1 * mul;
    }
  }
};
</script>

If you prefer using watch for this functionality, remember to add an additional check to prevent an endless loop:

watch: {
  value1(val) {
    const tmp = val * mul;
    if (tmp !== this.value2) {
      this.value2 = tmp;
    }
  },
  value2(val) {
    const tmp = val / mul;
    if (tmp !== this.value1) {
      this.value1 = tmp;
    }
  }
},

It's important to note that while multiplying by x and then dividing by x should yield the same number mathematically, working with floats (javascript's number type) introduces potential exceptions like NaN or rounding issues. Therefore, the simpler and recommended approach is using the input event-listener method.

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

Troubleshooting the failure of the addEventListener mouseEvent in an Angular environment

Recently, I've been encountering an issue with adding addEventListener to dynamically created HTML canvas elements. Everything was working fine before, but now none of the events seem to be triggered. Below is the code snippet I am currently using: t ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

JavaScript - Output an undefined value of a property within a function

While the question of checking for null or undefined values has been raised before, I am encountering a unique issue. I have created a function to split a string, which works perfectly. However, when I pass a null or undefined value, the program stops. Ins ...

PHP response triggers AJAX autocomplete functionality in JavaScript

The autocomplete hints are not displaying any response for me. Here is the jQuery code that I am using: jQuery( ".newtag_new" ).autocomplete({ minLength: 0, source: function( request, response ) { jQuery.ajax({ type: 'GET ...

How can you count the number of times a specific object key appears in JavaScript without relying on a for

I am looking for a way to determine the total number of residents in a particular city without relying on a traditional for loop. Can you help me understand how to achieve this using the given function? function tallyPeopleInManchester(people) { /* Th ...

Sort information based on the initial letter

My challenge is to accurately filter data by the starting letter only, not including middle letters. For example, if I have the word "Karnataka" and want to filter by the letter "K", searching with middle letters like "rna" still filters the result. Howe ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Similar to `util.inspect` in Node.js, Deno also has a function

Is there a utility function in Deno that can stringify an Object or primitive similar to Node.js util.inspect? For instance, if I have a JSON object in Node.js and want to display its contents: > m = {k1:'v1', k2:'v2'} { k1: ' ...

Issue with box shadow appearing incorrectly as element content increases in size while the body has an image background

After applying a box shadow to the header div, I noticed that the box shadow doesn't display properly when the hidden elements within the header are revealed. <div id="header"> <div id="logo"> <a href="#"><img src="logo.png" ...

The filter function in JavaScript's Array is malfunctioning on Internet Explorer version 7

My web application includes a jQuery plugin that is functioning correctly in Internet Explorer 10 and 11. However, it is not working in IE 7. Upon investigation, I discovered that the value of the filter method is showing as undefined. The line of code th ...

common problem in JavaScript involving childNodes

As someone new to JS, I'm reaching out after spending a couple of hours searching for a solution (it's currently 3:00am and I'm desperate to get some sleep). So, your help is greatly appreciated. My goal is to locate the child node within a ...

Touch events causing issues with scrolling due to knockout event binding

I encountered an issue with touchstart and touchmove events using knockout event binding where scrolling would get stuck (no preventDefault) and I also had trouble getting the click event to work properly. Interestingly, when I applied these events with ...

Is there a way to display the JavaScript widget exclusively on the homepage or main page

How can I limit the display of a Twitter widget on my blog page to only show on the main page and hide it when visitors navigate to sub-pages or individual blog entries? ...

What is the best way to pass on the isPending status (from useTransition) to parent components?

In my codebase, I have a standard component known as ClientButton. This component essentially wraps a Server Action using startTransition to create an event handler: 'use client'; export default function ClientButton({ onClick, buttonText, class ...

What is the functionality of click-cell.bs.table?

Is it possible to expand the row below a table by clicking on a cell in the row above with the use of click-cell.bs.table instead of click-row.bs.table? I am currently achieving this functionality using click-row.bs.table and bootstrap table. How can I m ...

Using openssl stream with node.js

I am facing an issue with my server running on TLS 1.0. Whenever I run the command below, it keeps giving me an endless stream of data on the terminal: ~$ openssl s_client -connect 'serveraddress':5000 The output is a real-time XML data stream ...

Sharing Props between React.js Components

After spending two days searching online, I am still struggling to pass an index from one element to a sibling element in order to display it. All I have been able to achieve so far is showing data inside every div, but I really want to only do it on the c ...

navLinkDayClick function from FullCalendar

Has anyone implemented navLinkDayClick in FullCalendar to trigger a custom event based on the selected date by fetching data from a database? I have successfully used eventClick to populate the calendar data, but I am facing difficulties in implementing t ...

A comparison between Angular JSON and JSONP $promise

When making a JSON call from my controller.js: $scope.userInvestors = userInvestors.query({UserID:$scope.user.uid}, function(userInvestors) { console.log("yep yer here"); } Using this $resource: factory('userInvestors', function($resour ...

What is the reason for Bower consistently choosing to download the Angular version 1.5.9-build.5086+sha...?

Struggling to manage my front end dependencies using bower.json. No matter how I specify the version of Angular in bower, a different version is downloaded every time. The issue is that many functionalities in my code rely on previous versions of Angular, ...