Child emitting to parent triggers an endless loop with a basic counter increment

I am having an issue with a fill in the blank question. I need to emit a signal back to the parent component each time an input is correct, so that when all inputs are correct, I can display a success message.

My approach was to use a simple counter to increment by one each time the $emit function is called in the parent. However, I keep running into an infinite loop on the last try and I can't figure out what I'm doing wrong. I have tried to simplify my code as much as possible to highlight the relevant parts for you to review. Could it be something related to how the parent component handles the loops of the question?

Any help or guidance would be greatly appreciated.

Parent Component

The parent component receives a JSON string like "There are *_* letters in the *_* alphabet" and splits it into spans for the text and inputs for the blanks, then reassembles it. The answers in this case would be 26 and English.

The problematic part in the parent component is the function questionSuccess()

<template>
  <div class="interactive interactive-vue-question interactive-vue-question-iv">
    <component
      :is="buildQuestion(index)"
      v-for="(item, index) in questionParts"
      ref="ivWrap"
      :key="index"
      :question-props="item.includes('*_*') ? matchedOptions[index] : item"
      @success="questionSuccess"
    />
  </div>
</template>

...
... (rest of the unchanged content)
...

Input Component

Each input in the sub-component is validated independently. When each input is correct, I want to emit a 'success' signal to the parent component. However, I end up getting stuck in an infinite loop when the last correct input is reached.

I trigger the 'success' event after validating if the input is correct

<template>
  <div class="iv-input-wrap" :class="[{'is-error': isError, 'is-correct': isCorrect}]">
    <input
      ref="iv"
      v-model="userInput"
      type="text"
      class="iv-input"
      :class="[{'is-correct': isCorrect, 'is-error': isError}]"
      :disabled="isCorrect"
    >
  </div>
</template>

...
... (rest of the unchanged content)
...

Answer №1

This answer was surprisingly straightforward.

By including .once in the event handler of the parent component, I was able to break the loop and successfully increment as intended.

<template>
     <div class="interactive interactive-vue-question interactive-vue-question-iv">
     <component 
       :is="buildQuestion(index)"
        ref="ivWrap"
        v-for="(item, index) in questionParts"
        :key="index"
        :questionProps="item.includes('*_*') ? matchedOptions[index] : item"
         @success.once="questionSuccess">
     </component>
   </div>
</template>

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

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

At initial glance on iOS, the login page remains hidden, but as I tilt the phone, the page fields slowly start to appear

Encountering a strange issue when accessing my application on iOS 11. Initially, the page fails to load completely with missing background and field labels. However, I am able to click on objects. Oddly enough, if I tilt my iPhone or zoom in, the page load ...

Using grid-template-areas in ReactJS function components does not function as expected

REMINDER: Check out and customize the code in CodeSandbox. This is a parent component with 5 children elements. Among them, 3 are React components and the remaining 2 are regular HTML buttons: import "./App.css"; import React from "react&qu ...

The failure of a unit test involving Jest and try-catch

I am facing an issue with creating unit tests using jest. exportMyData.js const createJobTrasferSetArray = async () => { const data = exportData(); const jobTransferSet = []; try { data.forEach((element) => { const JobPathArray = el ...

Troubleshooting the issue: Node.js application unable to utilize Mongodb's $addToSet functionality

I'm having an issue with mongo's $addToSet function not properly adding a Store to my stores array (where I have commented out seemed to work), resulting in duplicate IDs. Can anyone help me identify my mistake and suggest a solution? Thank you. ...

Incorporating a file from a specific directory in AngularJS

Every time I execute /sites/all/themes/theme/js/controller.js $scope.template = 'partials/tpl.html' /sites/all/themes/theme/js/index.html <div ng-include='template'></div> /sites/all/themes/theme/js/partials/tpl.html & ...

Look for a file within a directory based on its name without knowing the file extension

I am seeking a way to locate a specific file in a designated directory based on its name, without prior knowledge of its file extension. app.get("/test/:id", (req, res) => { const mongo_id = req.params.id; const file_path = ...

Identifying differences in a Knockout view model

While it may seem like a simple question, is there actually a straightforward method to identify if there has been a change in any property of a knockout view model? ...

PHP server-side detects empty AJAX post requests

I am encountering an issue while making an AJAX request to a PHP controller using jQuery ajax. The problem arises when attempting to access the posted data in PHP, as the $_POST variable is empty. Below is the function causing the trouble: function GetSer ...

Java's equivalent to the return function in JavaScript

Currently, I am in the process of adapting three.js into Java while also incorporating my own modifications and enhancements. One specific challenge I am facing involves determining the best approach for managing reflection within the code. As part of thi ...

How can I place an icon on a specific location in a Highcharts map?

I am currently utilizing Highcharts to showcase maps within my application. I am aiming to achieve two specific functionalities: 1) Upon clicking on any area, I want that area to be highlighted in red {completed} 2) Upon clicking on any area, I intend f ...

Exploring the method to reveal the password hidden field in MVC by utilizing the Html helper

@Html.Password("password", null, new { @class = "form-control frmField", placeholder = "Password" }) I want to incorporate a button that when clicked will make the password visible. I know this can be achieved using jQuery or Javascript, but I am unsure h ...

Choose between using a function as a parameter or an instruction when making a selection based on change

I am curious about the distinction between the following two sentences: $('#select').on('change', function() { Manager.doRequest(); }).trigger('change'); And these variations: $('#select').on('change&apos ...

Checkbox value not being accurately retrieved by Struts2 page

I have a form that captures phone information for two different phones, with each phone having its own set of details. If the user enters the same phone number for both phones, the second checkbox is automatically checked using the JavaScript code below: ...

Accessing an image from a directory using Javascript

I have a simple question that I need help with. In my code, I currently pull images from a website using this syntax: icon: 'http://i45.tinypic.com/2yua8ns.png'. However, I would like to use something like this instead: icon: '\images/i ...

How can we properly access the DOM element generated by an {#each} loop in Svelte when it is clicked?

Using Svelte's {#each} functionality, I am reactively loading elements in the following way: {#each $items as item} <div> <Button on:click={someFunction}>{item.text}</Button> (*) </div> {/each} (*) a component t ...

What is the best way to transfer information from JavaScript to a JSON database using the fetch API?

Within the userDB.json file, it appears as follows; [{ "username": "john", "xp": 5 }, { "username": "jane", "xp": 0 } ] Inside the app.js file ; async function getUsers() { le ...

An error is thrown when trying to retrieve Objects: Uncaught TypeError - Object function ParsePromise()

By obtaining a Document object with its id, the following code proceeds to locate corresponding sections based on the object. The document identifies a Parse object and document.toJSON converts this into a Javascript object. Furthermore, sections represent ...

Detection of JavaScript scroll event triggered by programmatic scrolling on an iOS device

I am working on an iOS app that utilizes a UIWebView. The web view contains javascript that responds to scroll events triggered by tapping on either side of the web view. However, I have encountered an issue where the javascript does not detect scroll even ...

Choose the Enum in a dynamic manner

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. During runtime, the specific country name is determined (it could be either INDIA, USA, or AUSTRALIA). Is it possible to select the correct enum based on the country name at runtime? For in ...