How to dynamically set resource Id from JS?

  • Goal:
    From a JS script call a query for each element of a given array whereas the array defines the resourceId that the same SQL query should be run on.

  • Steps:

  • created all resources for my different DBs
  • in my app, created a query and clicked the fx button and pre-selected one of the DB resources.
  • created a JS script that has a const dbs = ['resource-id-here1', 'resource-id-here2', ...]
  • tried to trigger via:
.. = Promise.all(dbs.map(id => {
  query1.resourceNameOverride = id;  // seems to have no effect
  return query1.trigger();
}));

This results in resolved promise values all with the same DB being used (the one that is pre-selected).

How do I trigger the same query, but with different resource ids without having to hard-code/manually create a query for each resource/db in my app?

Hello @WonkyDonky Welcome to the Retool Community,

To dynamically run a query on multiple resources, create a new query instance for each resource ID instead of modifying resourceNameOverride.

const dbs = ['resource-id-here1', 'resource-id-here2', 'resource-id-here3'];

const results = await Promise.all(dbs.map(id => {
  const newQuery = new Query({ name: 'baseQuery', resource: id });
  return newQuery.trigger();
}));

console.log(results);

This ensures each query runs with the correct resource. Using Promise.all executes them in parallel. If you need sequential execution, use await inside a loop.

3 Likes

Hi, parallel is intended. Query is not defined, in which version was it introduced? Also, I couldn't find this class in the Retool documentation, do you have the link handy?

Couldn't find an edit button

In case you meant the actual query, if I use new query1() it says, that it's not a constructor

Anyone knows a solution to this problem?

Hey @WonkyDonky

My apologies. Instead of passing IDs in the initial response, you can directly utilize the additional scope and include the multiple IDs you wish to transmit. This approach is generally preferred. : Additional scope .

5 Likes