Triggering a JS Query when a global state changes

  1. My goal:

I want to automatically run a JS Query whenever a global state variable (refreshSignal.value) changes.

  1. Issue:

JS Queries don’t seem to react to changes in global state. Even when I reference {{ refreshSignal.value }} in the query or in the “Disable query” condition, the JS Query does not re-run when the variable updates. It only runs if I explicitly call .trigger(), or if I set it to run periodically / on page load.

  1. Steps I’ve taken to troubleshoot:
  • Tried putting {{ refreshSignal.value }} in the JS Query directly.
  • Tried controlling with “Disable query” (e.g., {{ !refreshSignal.value }}).
  • Verified that refreshSignal.value is updating correctly.
  1. Additional info:
  • Running on Retool Cloud.

:point_right: My question: What’s the right way to make a JS Query automatically run when a global state changes?

1 Like

Hey @jeanS, Welcome to Retool Community.

I understand your issue — this exact problem has been discussed before in the forum here: Force run JS code to rerun when variable changes.

The working solution shared there is as follows:

  1. Create a sample resource query (e.g. a “Query JSON with SQL”).
  2. Inside the query, simply reference your state variable like this:
SELECT 
{{ monthlyDataState.value }}
  1. Set the query’s Run behavior to Automatic so that it reacts whenever the variable changes.
  2. In the Success event handler of this resource query, trigger your JS query.

That way, whenever monthlyDataState.value updates, the resource query automatically runs, and the success handler will in turn fire your JS query.

Here’s a screenshot for reference:

This approach is a reliable workaround since JS queries don’t natively re-run/automatic run behavior on global state changes. It ensures your logic always stays in sync with updates to the variable without needing manual triggers each time.

Hope this clears things up and gives you a smooth way forward :rocket:

3 Likes

I'm not sure of a "right way" but the workaround I use is to have a "dummy" JSON SQL query.
SQL queries will trigger when a variable value changes, whereas JS queries do not.

eg
global variable "myGlobalVar"
page level js Query "myResponseQuery"
page level JSON SQL Query "dummyResponseHandler"

the json query triggers every time the global var changes. on success it runs my js query
the js query shows the notification with the new value of the global var

1 Like

Thank you nice workaround :slight_smile:

1 Like