JavaScript API reference

Learn about built-in JavaScript functionality in Retool.

Retool's JavaScript APIs help you build complex functionality in apps and workflows. You can use these methods wherever you can write JavaScript in Retool.

Utility methods

Use these methods to interact with the Retool app interface.

utils.confetti()

Shows confetti animation.

Syntax

utils.confetti()

Return value

None.

Example

Show the confetti animation.

utils.confetti();

utils.downloadFile()

Generates a file containing the specified data which is then downloaded by the user's browser.

To download data from a Table component, use utils.exportData.

Syntax

utils.downloadFile(data, fileName, fileType)
data
required

A string or object to specify the data to download. To download Base64-encoded data, provide an object that contains the parameter base64Binary with the Base64-encoded value.

fileName
optional

A string to specify the downloaded file name. Defaults to "file" if not set.

Return value

None.

Examples

Download the results of getUsersQuery as a YAML file named users-data.

utils.downloadFile(getUsersQuery.data, "users-data", "yaml");

Download BASE64_STRING as a CSV file named users-data.

utils.downloadFile({ base64Binary: BASE64_STRING }, "users-data", "csv");

utils.downloadPage()

Generates a PDF file of the current view which is then downloaded by the user's browser. It excludes Custom, HTML, and IFrame components.

Syntax

utils.downloadPage(fileName, options)
fileName
optional

A string to specify the name of the downloaded file.

options
optional

An object that controls the PDF formatting and selectors and components to exclude.

ParameterTypeDescription
selectorsToExcludearray (optional)Any selectors to exclude from the PDF.
componentsToExcludearray (optional)Any components to exclude from the PDF.
scalenumber (optional)The resolution of the page to export. Defaults to window.devicePixelRatio.
fullScreenboolean (optional)Whether to download the page in presentation mode. Defaults to false.

Return value

None.

Example

Download a PDF of the current view, excluding container1 and its nested components, as users_dashboard.pdf.

utils.downloadPage("users_dashboard", { componentsToExclude: ["container1"] });

utils.exportData()

Generates a file containing data for the specified Table component which is then downloaded by the user's browser.

Syntax

utils.exportData(data, fileName, fileType)
data
required

An object or array containing the table data to export. data can be the table's data, normalizedData, or displayedData.

fileName
optional

A string to specify the name of the downloaded file. Defaults to "export".

fileType
optional

A string to specify the type of the downloaded file. One of csv (default), tsv, xlsx, or json.

Return value

None.

Example

Download usersTable.data as a CSV named usersData.

utils.exportData(usersTable.data, "usersData");

utils.getCurrentPosition()

Retrieves the user's current geographical location, if allowed by the user.

Syntax

utils.getCurrentPosition(options)
options
optional

An object that contains a callback function.

ParameterTypeDescription
onSuccessfunctionA callback function to trigger when the method runs successfully.

Return value

An object that contains a timestamp and a coords object that contains the following properties.

PropertyDescription
latitudeThe position’s latitude in decimal degrees.
longitudeThe position’s longitude in decimal degrees.
speedThe velocity in meters per second.
accuracyThe position’s accuracy in meters.
altitudeThe position’s altitude in meters above sea level.
altitudeAccuracyThe altitude’s accuracy in meters.
headingThe direction of travel in degrees from true north.

Example

Retrieve the coordinates of the current user and calls updateMap upon success.

await utils.getCurrentPosition({
  onSuccess: function (data) {
    updateMap.trigger();
  },
});

utils.openApp()

Opens a Retool app. The app must be in the same organization as the caller of openApp.

Syntax

utils.openApp(appUuid, options)
appUuid
required

A string to specify the UUID of the app to open. appUuid is in the retoolContext state while in edit mode and in the URL of the app.

options
optional

An object that controls how to open the app.

ParameterTypeDescription
queryParamsobject (optional)An object of query parameters to pass into the app.
newTabboolean (optional)Whether to open the app in a new tab. Defaults to true.

Return value

None.

Example

Open an app with the query parameters source=updateUsersApp.

utils.openApp("371ac2f8-3aaf-11ed-8b80-836b0df4638d", {
  queryParams: { source: "updateUsersApp" },
});

utils.openUrl()

Opens a URL.

Syntax

utils.openUrl(url, options)
url
required

A string to specify the URL to open.

options
optional

An object that controls how to open the URL.

ParameterTypeDescription
newTabboolean (optional)Whether to open the URL in a new tab. Defaults to true.
forceReloadboolean (optional)Whether to prevent client-side routing and force a page reload. Defaults to false.

Return value

None.

Example

Open Retool Docs in the current tab.

utils.openUrl("https://docs.retool.com", { newTab: false });

utils.showNotification()

Shows a notification message on the top right corner of the screen.

Syntax

utils.showNotification(options)
options
optional

An object that controls the notification settings.

ParameterTypeDescription
titlestring (optional)Title for the notification modal. Defaults to "Notification".
descriptionstring (optional)Description of the notification. Defaults to an empty string.
notificationTypestring (optional)The type of notification. One of info (default), success, warning, or error.
durationnumber (optional)The length of time, in seconds, to display the message. Defaults to 4.5 seconds.

Return value

None.

Example

Display a success message after deleting a user.

utils.showNotification({
  title: "Deleted user",
  description: "Successfully deleted user.",
  notificationType: "success",
  duration: 3,
});

File utility methods

Use these methods to parse CSV, JSON, and XLSX files.

fileUtils.parseCSV()

Parses a CSV file that resolves to the file's contents.

Syntax

fileUtils.parseCSV(value, options)
value
required

A string to specify the Base64-encoded CSV file.

options
optional

An object that controls settings for the file parsing.

ParameterTypeDescription
headerboolean (optional)Whether the CSV file contains a header. Defaults to true.

Return value

Returns a Promise that resolves to a list of objects with one key per column.

Example

Parse the contents of the file uploaded using uploadFileButton. The results array represents each row of the CSV, where results[0] is the first row.

const results = await fileUtils.parseCSV(uploadFileButton.value[0]);

fileUtils.parseJSON()

Parses a JSON file that resolves to the file's contents.

Syntax

fileUtils.parseJSON(value)
value
required

A string to specify the Base64-encoded JSON file.

Return value

Returns a Promise that resolves to an object with the file's contents.

Example

Parse the contents of the file uploaded using uploadFileButton into the results array.

const results = await fileUtils.parseJSON(uploadFileButton.value[0]);

fileUtils.parseXLSX()

Parses an XLSX file that resolves to the file's contents.

Syntax

fileUtils.parseXLSX(value)
value
required

A string to specify the Base64-encoded XLSX file.

Return value

Returns a Promise that resolves to an object with the file's contents. The result contains an object for each sheet with a nested object for each row.

Example

Parse the contents of the file uploaded using uploadFileButton into the results array.

const results = await fileUtils.parseXLSX(uploadFileButton.value[0]);

Array and object utility methods

Use these methods to format data as arrays and objects.

formatDataAsArray()

Formats data as an array of objects or an array of arrays.

Syntax

formatDataAsArray(data, outputArrayOfArrays)
data
required

An object to convert to an array.

outputArrayOfArrays
optional

A boolean to specify whether to return an array of arrays. Defaults to "false".

Return value

An array of objects or an array of arrays.

Example

Format data returned from a SQL query as an array, where each item represents one row of the query result.

formatDataAsArray({
  id: [2, 5],
  first_name: ["Rosemary", "Elizabeth"],
  last_name: ["Rogers", "Meets"],
});
[
  {
    "id": 2,
    "first_name": "Rosemary",
    "last_name": "Rogers"
  },
  {
    "id": 5,
    "first_name": "Elizabeth",
    "last_name": "Meets"
  }
]

formatDataAsObject()

Formats data as object.

Syntax

formatDataAsObject(data)
data
required

An array to convert to an object.

Return value

An object containing data.

Example

Return a Table component's recordUpdates property, an array, as an object grouped by common keys.

formatDataAsObject([
  {
    "id": 2,
    "first_name": "Rosemary",
    "last_name": "Rogers",
  },
  {
    "id": 5,
    "first_name": "Elizabeth",
    "last_name": "Meets",
  },
]);
{
  id: [2, 5],
  first_name: ["Rosemary", "Elizabeth"],
  last_name: ["Rogers", "Meets"],
}

Local storage methods

Use localStorage methods to save data locally to the browser.

localStorage.clear()

Clears all keys and values from Retool's localStorage.

Syntax

localStorage.clear()

Return value

None.

Example

Clear all keys and values from Retool's localStorage.

localStorage.clear();

localStorage.setValue()

Store a value to Retool's localStorage.

Syntax

localStorage.setValue(key, value)
key
required

A string to specify the name of the key to set.

value
required

A string, object, boolean, number, or array to set as the key's value.

Return value

None.

Example

Store localUserCookie value as user.cookieValue.

localStorage.setValue("localUserCookie", user.cookieValue);

Temporary state methods

Use temporary state methods to temporarily store data within a Retool app.

temporaryState.setIn()

Sets the value of temporaryState at a specified location.

Syntax

temporaryState.setIn(path, value)
path
required

An array of keys or indexes to select, where each item represents a key or index in the path to the object to update.

value
required

A string, object, boolean, number, or array to set as the value at the path.

Return value

None.

Example

Set the second item of key1, nested in object1 in tempState, to value2.

tempState.setIn(["object1", "key1", 1], "value2");

temporaryState.setValue()

Sets the value of a temporary state variable.

Syntax

temporaryState.setValue(value)
value
required

A string, object, boolean, number, or array to set as the value of the temporary state object.

Return value

None.

Example

Set the value of tempState to the sorting method used on usersTable.

tempState.setValue(usersTable.sort);

Query methods

Use query methods to control when and how queries run.

query.invalidateCache()

Declares the cached results of the query invalid. The next time the query is triggered, it will return fresh results.

Syntax

query.invalidateCache()

Return value

None.

Example

Invalidate the cache for the getUsers query.

getUsers.invalidateCache();

query.reset()

Clears the data and error properties of the query.

Syntax

query.reset()

Return value

None.

Example

Clear the data and error properties of the getUsers query.

getUsers.reset();

query.trigger()

Runs the query.

Syntax

query.trigger(options)
options
optional

An object to pass to the query and to control behavior after the query returns.

ParameterTypeDescription
additionalScopeobject (optional)Additional context to pass to query.
onSuccessfunction (optional)Function to call after query successfully returns.
onFailurefunction (optional)Function to call on query failure.

Return value

Returns a Promise that resolves to the query's data property.

Example

Trigger getUsers with additional scope, and call different functions if the query succeeds or fails.

await getUsers.trigger({
  additionalScope: { userId: user1.id },
  onSuccess: function (data) {
    console.log(data);
  },
  onFailure: function (error) {
    console.log("Error");
  },
});