Home > Enterprise >  Nuxtjs/Vuejs Watchers running into endless loop due to change in the values
Nuxtjs/Vuejs Watchers running into endless loop due to change in the values

Time:10-10

I am developing a Nuxtjs/Vuejs application to convert the XML->JSON and vice versa. Users can provide the values to the textarea and these textareas are managed by CodeMirror.

The textarea is bonded to V-model from the Vex Store. I have added Watchers on these Vuex state variables so whenever they change the values I want to convert the respective data to a different format. I.e if XML value changes then XML needs to be converted to JSON. Similarly if JSON value changes then JSON needs to be converted to XML.

When I copy-paste the XML into XML textarea then for the first time it works perfectly but I make any modification and try to introduce some Syntax error in XML then I run into the issue where the watchers starts calling each other and endup in endless loops.

I have provided the sample code within CodeSandbox: https://codesandbox.io/s/boring-water-g14zd?file=/pages/index.vue

Steps to recreate the issue:

  1. Provide the Sample XML in the XML Area:
<root>
<name>Batman</name>
</root>

We get the output as: CONVERT TO JSON-LD within the JSON textarea

  1. Now make the modification to the same XML within the XML Textarea by removing some anchor tab (</>)

Now both textarea are populated with Error Message but in reality I want only the JSON area to be populated with Error Message indicating whats wrong in XML and Modified XML should be as it is within the XML Area.

If you observe the Console then you can see that I am running into a cyclic issue due to the watchers. I want to call the jsonConverter whenever the XML value changes within the XML Editor and same vice versa but I do not want to get into XMLConverter after converting to JSON.

Can someone please explain to me how can I avoid this issue? I am running out of all ideas as I am unable to get the onChange for the CodeMirror directly I am using the Watchers. If someone has any idea or solution it would be really great as I have spent more than a day to resolve this but ended up with nothing.

CodeSandBox: https://codesandbox.io/s/boring-water-g14zd?file=/pages/index.vue

CodePudding user response:

I think the main issue here is that your JSON and XML values are being controlled in too many places. The v-models, the watchers, and the CodeMirror events.

I have changed your code and made CodeMirror the main controller of the values. You can see the result here: CodeSandbox

To prevent the parsing loop, I've compared the new values with the ones saved in the store. If they are the same, then the value has been set by ourselves. If they differ, then the user has changed it and we should try to parse.

  • Related