How to clear a text component between query runs?

I’m trying to display the steps of my query by populating a text component (instead of using console.log). This works well the first time:

textOutput.setValue('Init:');
return myQuery.trigger({
    onSuccess: (data) => {
      textOutput.setValue(textOutput.value += `\n\nNext step ${JSON.stringify(data)}`)
    },
  });

// I see:
// Init:
// Next step [data1, data2]

The problem is that if I run the query two times more, I see this:

// Init:
// Next step [data1, data2]
// Next step [data1, data2]
// Next step [data1, data2]

I have no idea why this is happening.

@nacho are you running this as a JS query? What’s the expected behavior?

Yes, as a JS query.

The expected behavior would be this every time:

// Init:
// Next step [data1, data2]

And you’re triggering this JS query every time your other query runs? Or from a button / manually?

I’m triggering it with a button, but when I preview it manually I get the same result.

Hi there! So the JS code is a little tricky here. Every external function, in this case .trigger and .setValue, happens asynchronously together at the end of the JS query using the values that are defined at that point internally in the JS code. So what is happening here is:

  1. Query runs, evaluates textOutput.value
  2. Query completes
  3. textOutput’s value is set to ‘Init:’
  4. myQuery is run, with an onSuccess function that is defined using the original value of textOutput.value
  5. textOutput’s value is set to that textOutput.value property, with the data +='ed to it.

To put it another way, here’s what you could expect from this code section:

let val = tempState.value;
console.log(val); //returns "Original Value"
tempState.setValue("Hello!");
console.log(tempState.value); //returns "Original Value"
-----code ends----
//In the browser console you'll see
Setting value of tempState to "Hello!"

Thanks, Alex. I understand.

How do you suggest I go about it? What’s the best way to show the process if I have JS query that’s firing off multiple queries?

In this specific example, it doesn’t actually seem like the original value of the textOutput matters? If so, something simple like this would work but I feel like I’m missing the overall goal here:

    let queryLog = 'Init:';
    return myQuery.trigger({
        onSuccess: (data) => {
          textOutput.setValue(queryLog += `\n\nNext step ${JSON.stringify(data)}`)
        },
      });
1 Like