Pass Parameters to Queries
This page describes how to use the run() function in a loop to pass different parameters to your query each time it runs.
In some cases, like running a query inside a loop, different parameters may need to be passed to the query each time with values contextual to the execution.
For this, you can use the run()
function's params
argument to pass an object of key-value pairs into your query. You can access these values within the query using {{ this.params.key }}
.
As an example, the snippets below fetch specific users from the mock users database based on their id
value. Below, you'll see how to configure a query and a helper function to take an array of ids and run the query in a loop for each of them.
To begin, you should have a query to which you'd like to pass contextual parameters.
Create a JS Object and rename it
utils
. This is where you write your helper function that calls the query and handles its responses.Create a function that calls your query's
run()
function in a loop, using therun()
function's first argument to pass your parameter. On completion, the results of the queries are mapped into an array and stored in the Appsmith store.// Using promise syntax
getByIds: async (ids) => {
const queries = ids.map(id => {
// each iteration of the loop will pass the next `id` from the `ids` array.
return GetUserById.run({"id": id})
})
Promise.all(queries)
// once the queries have settled, they results are stored in an array in the Appsmith store.
.then(values => storeValue("results", values))
}In the query where you want to pass parameters, reference the params with
{{this.params.id}}
.To execute the query loop, configure a trigger or widget action that calls your helper function in the JS Object:
{{ utils.getByIds([1, 4, 8, 34, 16]) }}
Wherever you want to use the results of the queries, you can reference the array containing those results from the Appsmith store like below:
{{ appsmith.store.results }}