Skip to main content

Changelog

Updates, changes, and improvements at Retool.

Run an API request for each row in a table

· 3 min read

This examples makes an API request for each row in a table, and then shows any errors returned in the process.

1. Add a table

Add a Table component to your app. Select Use an array in the Data source dropdown menu, then paste this JSON into the Data source attribute.

[
{
"id": 1,
"name": "Hanson Deck",
"email": "hanson@deck.com",
"sales": 37
},
{
"id": 2,
"name": "Sue Shei",
"email": "sueshei@example.com",
"sales": 550
},
{
"id": 3,
"name": "Jason Response",
"email": "jason@response.com",
"sales": 55
},
{
"id": 4,
"name": "Cher Actor",
"email": "cher@example.com",
"sales": 424
},
{
"id": 5,
"name": "Erica Widget",
"email": "erica@widget.org",
"sales": 243
}
]

2. Create a query

Create a query using the RestQuery (restapi) resource. Set the Action type to Post and use this URL: https://approvals.tryretool.com/api/users/approve?email={{table1.data[i].email}}. The URL parameters are populated automatically.

By default, the i property is 0 but JavaScript in a subsequent step will increment this value so the query runs on each row.

Adding a REST query

3. Add a Button and Text components

Add a Button and two Text components to your app. Status shows the query's progress and Errors displays any errors while the query runs.

4. Write the JavaScript query

Create a JavaScript query named query2 and add the following JavaScript.

var rows = table1.data;
var errors = "";
var total = rows.length;

function runQuery(i) {
// Update the Status text
Status.setValue("Progress: " + (i.toString() + "/" + total.toString()));

if (i >= rows.length) {
console.log("Finished running all queries");
return;
}

console.log("Running query for row", i);

query1.trigger({
additionalScope: { i: i }, // This is where we override the `i` variable
// You can use the argument to get the data with the onSuccess function
onSuccess: function (data) {
runQuery(i + 1);
},
onFailure: function (error) {
// Update the Errors text
errors += "Found error at line " + i.toString() + ": " + error + "\n\n";
Errors.setValue(errors);
runQuery(i + 1);
},
});
}

runQuery(0);

5. Add an event handler to your button

After saving query2, add an event handler to your button that triggers the JavaScript query.

Now click the Submit button to test the app. As the query runs on each row, the status updates and errors are displayed. Since the API endpoint at https://approvals.tryretool.com/api/users/approve doesn't exist, all the requests fail.