top of page
Logo of top retool developers and retool agency

Using additionalScope in your Queries

The additionalScope feature in Retool enhances query flexibility and reusability by allowing dynamic variable passing. This powerful tool enables developers to execute the same query with different parameters tailored to specific use cases.


By leveraging additionalScope, you can create more adaptable and efficient applications. This feature is handy for scenarios requiring dynamic inputs, such as user interactions or varying data conditions. In this article, you will learn how to use  Retool additionalScope to its fullest possibility.


How additionalScope Allows for Dynamic Query Execution by Passing Extra Variables


How additionalScope Allows for Dynamic Query Execution

The additionalScope object enables dynamic query execution by allowing you to pass extra variables during query execution. You can define a query once and use it in various contexts by supplying variable values as needed. For example, if you have a query that fetches user data based on user ID, you can use additionalScope to pass the user ID dynamically when the query is triggered.


Example Usage:

const user = { id: 1, name: "test" };

await getUserById.trigger({

  additionalScope: { userId: user.id },

  onSuccess: function (data) {

    console.log(data);

  },

  onFailure: function (error) {

    console.log("Error");

  },

});


In this example, the getUserById query is triggered with the userId variable passed through additionalScope, allowing the same query to be reused for different user IDs without modification.


Refer to the Retool documentation on query objects and advanced query options for more detailed information.


In the following section, learn the steps to use Retool additionalScope.


How to Use additionalScope in Retool?


How to Use additionalScope in Retool

additionalScope in Retool enables you to execute queries with varying inputs without hardcoding values, making your applications more adaptable to different contexts and user interactions. You can pass variables to your queries that are unavailable in the global scope. By using additionalScope, you can keep your queries clean and flexible.


For more details, you can refer to the Retool documentation.



Using the .trigger() Method with additionalScope to Initiate Queries


One can use the .trigger() method to execute a query programmatically. When you use .trigger(), you can include an additionalScope object to pass extra variables to the query. It makes your queries more dynamic and adaptable to different contexts.


Example Usage:

const user = { id: 1, name: "test" };

await getUserById.trigger({

  additionalScope: { userId: user.id },

  onSuccess: function (data) {

    console.log(data);

  },

  onFailure: function (error) {

    console.log("Error");

  },

});


In this example, the userId variable is passed to the getUserById query through additionalScope.


Key Guidance on the structure for passing `key:value` pairs within the additionalScope object.


When using additionalScope, you structure it as an object containing key:value pairs. Each key represents the variable's name you want to pass, and the value is the corresponding data you want the query to use.


Example Structure:

await myQuery.trigger({

  additionalScope: {

    variable1: "value1",

    variable2: 123,

    variable3: true

  }

});


It allows the query myQuery to access variable1, variable2, and variable3 during its execution.


Explanation of How to Utilize additionalScope Data within the Query Editor


To utilize additionalScope data within the query editor, reference the variables directly in your query logic. For instance, in an SQL query or a REST API call, you can access the passed variables as if they were part of the query's local scope.


Example in SQL Query:

SELECT * FROM users WHERE id = {{ additionalScope.userId }}


Example in JavaScript Query:

const userId = additionalScope.userId;

return fetch(`/api/users/${userId}`)

  .then(response => response.json())

  .then(data => data);


In both examples, additionalScope.userId dynamically injects the user ID into the query.


By leveraging additionalScope, you can make your Retool applications more dynamic and context-aware, enhancing their functionality and responsiveness. For more detailed information, you can explore the Retool documentation and best practices for using JavaScript in Retool.


Check out the following section's common use case for Retool additionalScope.


Common Use Cases for additionalScope in Retool


Common Use Cases for additionalScope in Retool

Read the common use cases for additionalScope in detail from this section and use additionalScope like a pro!


Iterating Over an Array to Trigger a Query for Each Item and Compiling Results


One powerful use of additionalScope is iterating over an array of items to trigger a query for each item. You can use JavaScript's Promise.all() to handle asynchronous operations and compile results.


Example:

const items = [1, 2, 3, 4, 5];

const results = await Promise.all(items.map(async (item) => {

  return await myQuery.trigger({

    additionalScope: { itemId: item },

  });

}));

console.log(results);


In this example, the query myQuery is triggered for each item in the array, passing itemId dynamically through additionalScope.


Executing Queries with Different Filters Using additionalScope to Modify the Filter Value


Using additionalScope to modify filter values lets you dynamically execute the same query with different parameters.


Example:

const filterValue = 'active';

await myQuery.trigger({

  additionalScope: { status: filterValue },

});

This example dynamically sets the status filter to 'active' when triggering the query myQuery.


Workflow for a Query with a WHERE Clause, a Table, and Buttons for Different Filters


You can create a workflow where a query with a WHERE clause is filtered based on user interactions with buttons. The query retrieves data from the selected filter and displays it in a table.


Example:


SQL Query with WHERE Clause:

  • SELECT * FROM users WHERE status = {{ additionalScope.status }};


Table Component:


Filter Buttons:

  • Create buttons for different filters (e.g., Active, Inactive).


Button Event Handlers:


Set up click event handlers to trigger the query with the appropriate filter value.

activeButton.onClick = async () => {

  await myQuery.trigger({

    additionalScope: { status: 'active' },

  });

};


inactiveButton.onClick = async () => {

  await myQuery.trigger({

    additionalScope: { status: 'inactive' },

  });

};


Setting Up Click Event Handlers for Buttons to Trigger the Query with a true/false isChecked Variable


Buttons can be used to set a boolean filter dynamically in your queries using additionalScope.


Example:


Query with Boolean Filter:

  • SELECT * FROM tasks WHERE isCompleted = {{ additionalScope.isChecked }};


Buttons for True/False Filters:

  • Create buttons to filter tasks based on completion status.


Event Handlers:

  • Configure the buttons to trigger the query with isChecked set to true or false.

               completeButton.onClick = async () => {

  await myQuery.trigger({

    additionalScope: { isChecked: true },

  });

};


incompleteButton.onClick = async () => {

  await myQuery.trigger({

    additionalScope: { isChecked: false },

  });

};


By using additionalScope in these ways, you can enhance the flexibility and interactivity of your Retool applications, making them more responsive to user input and dynamic conditions. For more details, refer to Retool's query documentation and examples.

Jump on to the following section for the considerations when using the Retool additionalScope.


Considerations When Using additionalScope in Retool


Considerations When Using additionalScope in Retool

Check out the considerations when using additionalScope in detail in this section.

Refer to Retool's Query object and Event handlers documentation for more information.


Editor Behavior Regarding additionalScope Variables Highlighted in Red

When using additionalScope in Retool, you might notice the red highlighting of the variables that pass through within the query editor. This red highlighting indicates that the editor does not globally recognize these variables but dynamically injects them at runtime. This behavior is normal and indicates that additional variables must be resolved during the query's execution. This functionality allows for more dynamic and context-specific query parameters.


Support for Including Multiple Variables Within additionalScope to Enhance Query Flexibility

You can pass several key-value pairs within the additionalScope object, supporting the inclusion of multiple variables to dynamically adjust your query parameters based on the current context or user input.


Example:

await myQuery.trigger({

  additionalScope: {

    userId: 123,

    status: 'active',

    pageSize: 20

  }

});


In this example, myQuery is executed with three dynamically passed variables: userId, status, and pageSize.


Ensuring Correct Syntax Usage for additionalScope to Avoid Errors in Query Execution

The correct syntax for additionalScope is crucial to avoid errors during query execution. Here’s the proper way to structure and use additionalScope:

  • Correct Object Structure: Ensure structuring of the additionalScope as an object containing key-value pairs.

  • Variable References: In your query, refer to these variables directly. For example, in an SQL query:


SELECT * FROM users WHERE id = {{ additionalScope.userId }} AND status = {{ additionalScope.status }}

Example Syntax:

Await myQuery.trigger({

  additionalScope: { variableName: value },

  onSuccess: function(data) {

    console.log('Query succeeded:', data);

  },

  onFailure: function(error) {

    console.error('Query failed:', error);

  }

});


It ensures the query executes correctly and utilizes the variables passed via additionalScope.

For more detailed guidance, explore Retool's documentation on the Query object and event handlers. These resources provide comprehensive information on using additionalScope effectively and managing dynamic queries. Check out Retool for additional information.


You can also contact Toolpioneers, an agency that builds custom software applications quickly using Retool,  for complete guidance on using additionalScope in Retool. 

Commentaires


bottom of page