ToolJet/docs/versioned_docs/version-2.33.0/data-sources/custom-js.md
Akshay 2d08d889de
Release: Community changes (v2.34.0) (#9226)
* add custom resolvers info and editable row selection info (#9057)

* fix system requirements icon

* add auth info for webhooks and fix casing

* add regex custom validation info (#9068)

* [docs]: Marketplace 1.7 updates (#9085)

* [docs] Amazon redshift plugin

* make minor improvements

* add and update docs for marketplace 1.7

* update order of plugins in overview to match sidebar

* create new version

---------

Co-authored-by: Shubhendra <withshubh@gmail.com>

* add the latest version in the versions.json file (#9094)

* [docs]: Update PDF component (#9088)

* update PDF component

* merged with develop and added changes to the new version

* update docs favicon: (#9118)

* [docs] SSO revamp (#9031)

* add method to set default language

* update image settings through custom css and update screenshots for getting started and tooljet concepts (#9158)

* fix read documentation button

* fix formatting for setup icons (#9172)

* fix sidebar link for aws lambda

* Update static media (#9175)

* updated the screenshots

* reduced the gif size

* reverted the package.json file

* edited the zoomed in images and replaced some gifs with screenshots

* removed one gif

* update static media

* update file names

* update toolbar

* fix file names

* fix: dynamodb img path

* update media for org management dashboard

* fix: casing and formatting

* update workspace constant media

* update media in workspace settings and github

* update github sso

* minor change to github sso docs

* minor fix

* update google sso

* change includeCurrentVersion flag to false

---------

Co-authored-by: Asjad Ahmed Khan <iitasjad2001@gmail.com>
Co-authored-by: Asjad Ahmed Khan <60435499+2001asjad@users.noreply.github.com>
Co-authored-by: Karan Rathod <karan.altcampus@gmail.com>

* Feature: Engagespot plugin (#9012)

* feat(plugins): added engagespot plugin

* feat(docs): added engagespot plugin docs

* chore(engagespot-plugin): revised copywritings

* Feature: Databricks data source (#9174)

* plugin-created

* Databricks integration

* icon, error handling

* removed unrelated changes from marketplace and frontend package-lock.json removed runAsync and maxRows timeouts pending

* timeout implementation

* socket timeout and error handling

* resolve comments

* resolve comments2

* solved render issue test connection improvements

* solved undefined error

* fix TJDB not null value fail for is operation (#9055)

* fix TJDB not null value fail for is operation

* handling not null and null case insenstive values

* Support for marketplace plugin deploy on render preview app (#9221)

* Fix for marketplace error on render preview app

* add marketplace build command

* Adding new workflow for building marketplace plugin

* removed render app creation

* [:docs] Add documentation for Databricks plugin (#9224)

* add docs for databricks

* update databricks docs

* update docs

* remove ref to clusters

* bump to v2.34.0

* Fixed data source cypress failure (#9227)

* updated spec with required text

* updated mongodb and import spec

* updated import spec

---------

Co-authored-by: Karan Rathod <karan.altcampus@gmail.com>
Co-authored-by: Adish M <44204658+adishM98@users.noreply.github.com>
Co-authored-by: Midhun G S <gsmithun4@gmail.com>
Co-authored-by: Shubhendra <withshubh@gmail.com>
Co-authored-by: Aman Regu <amanregu@gmail.com>
Co-authored-by: Asjad Ahmed Khan <iitasjad2001@gmail.com>
Co-authored-by: Asjad Ahmed Khan <60435499+2001asjad@users.noreply.github.com>
Co-authored-by: Jobin Jose <129726530+jobin-logidots@users.noreply.github.com>
Co-authored-by: Syed Mohammad Akhtar Rizvi <85864291+ShazanRizvi@users.noreply.github.com>
Co-authored-by: blank0537 <111295371+blank0537@users.noreply.github.com>
Co-authored-by: Mekhla Asopa <59684099+Mekhla-Asopa@users.noreply.github.com>
2024-03-29 19:13:26 +05:30

139 lines
No EOL
6.3 KiB
Markdown

---
id: run-js
title: Run JavaScript code
---
You can write custom JavaScript code to interact with components and queries. To do that, you just need to create a new query and select **Run JavaScript Code** from the default datasources section.
<div style={{textAlign: 'center'}}>
<img className="screenshot-full" src="/img/datasource-reference/custom-javascript/defaultds.png" alt="Run JavaScript code" />
</div>
## JS parameters
JS parameters in RunJS queries offer a convenient way to customize JavaScript code execution without altering the code directly. You can add parameters by clicking the **Add** button in the RunJS query editor.
Each parameter requires:
- **Name**: Name for the parameter
- **Default value**: The value can be constant strings, numbers and object.
**Syntax for calling the parameter:** `parameters.<name>`
<div style={{textAlign: 'center'}}>
<img className="screenshot-full" src="/img/datasource-reference/custom-javascript/addparam.png" alt="Run JavaScript code" />
</div>
### Example: Alert a parameter
Let's create a new parameter named `object1` and set the value as object `{key1: 'value1'}` and use the alert js method to show the value on the pop-up.
Syntax:
```
alert(parameters.object1)
```
When the query is triggered the alert will show the parameters value.
<div style={{textAlign: 'center'}}>
<img className="screenshot-full" src="/img/datasource-reference/custom-javascript/popup.png" alt="Run JavaScript code" />
</div>
### Example: Providing custom parameters by calling another query
Let's demonstrate how to utilize parameters in RunJS queries and call one query from another by providing custom parameter values:
1. Begin by creating a new RunJS query named `multiply`. In this query, add the following parameters: **num1** with a default value of `10` and **num2** with a default value of `2`. To display the result, place a text component on the canvas and set its text to **{{queries.multiply.data}}**. Save and Run the query.
<div style={{textAlign: 'center'}}>
<img className="screenshot-full" src="/img/datasource-reference/custom-javascript/multiply.png" alt="Run JavaScript code" />
</div>
2. Now, let's create another RunJS query called `callMultiply`, where we will invoke the `multiply` query created earlier using custom parameter values. Here's the code snippet for `callMultiply`:
```js
queries.multiply.run({num1: 20, num2: 20})
```
By executing this code within `callMultiply`, we trigger the `multiply` query with specific values for its parameters.
<div style={{textAlign: 'center'}}>
<img className="screenshot-full" src="/img/datasource-reference/custom-javascript/callmultiply.png" alt="Run JavaScript code" />
</div>
With this setup, the `multiply` query can be called from other queries, such as `callMultiply`, by providing custom parameter values. This allows you to reuse the `multiply` query with different inputs and display the results accordingly.
## RunJS query examples
### Displaying random number
- Let's drag a **button** and a **text** widget inside a container widget.
- Click on the `+` on the query panel to create a query and select **Run JavaScript code** from the available datasources
- Write the code in **JavaScript editor** and save the query:
```jsx
const a = Math.floor(Math.random() * (10 - 1)) + 1;
return a;
```
:::tip
- The `return` statement is used to end the code and the value specified to the `return` statement will be stored in the `data` property of the query.
ex: `{{queries.runjs1.data}}`
- You cannot use `console.log` in Run JavaScript code
:::
- Let's edit the properties of widgets:
- Add an event handler to the button - Select **On Click** event, **Run Query** action, and select the `runjs1` query that we created. This will run the JavaScript code every time the button is clicked.
- Edit the property of text widget - In the text field enter **Random number: `{{queries.runjs1.data}}`**. It will display the output as Random number: *result from JS code*
<div style={{textAlign: 'center'}}>
<img className="screenshot-full" src="/img/datasource-reference/custom-javascript/jsrandom.gif" alt="Run JavaScript code" />
</div>
### Generating Unique ID
#### Code 1:
```js
var id = "id" + Math.random().toString(16).slice(2);
return id;
```
In this code, the resulting ID will have the format "id" followed by a sequence of random hexadecimal characters. For example, it could be something like "id2f4a1b".
#### Code 2:
```js
return String(Date.now().toString(32) + Math.random().toString(16)).replace(/\./g, '');
```
In this code, the resulting ID will have the format "timestamp + randomHex", where "timestamp" is the current time in base-32 and "randomHex" is a random hexadecimal value. This ID will be longer than the one generated by Code 1, and it could look like "2g3h1d6a4h3".
Both code snippets will produce IDs that are highly likely to be unique. However, Code 1 generates shorter IDs and follows a more straightforward approach with a fixed prefix ("id"). On the other hand, Code 2 generates longer IDs by incorporating the current timestamp and using a combination of base-32 and hexadecimal representations. The choice between the two methods depends on the specific requirements of the application and the desired length of the generated IDs.
:::tip Resources
- You can also write custom JavaScript code to get the data from **External APIs** and manipulate the response for graphical representation. Here's the [tutorial](https://blog.tooljet.com/build-github-stars-history-app-in-5-minutes-using-low-code/) on how we used custom JavaScript code to build an app using GitHub API.
- [Import external libraries](/docs/how-to/import-external-libraries-using-runjs) using RunJS.
- [Intentionally Fail](docs/how-to/intentionally-fail-js-query) a RunJS query.
- [Trigger query at specified intervals](/docs/how-to/run-query-at-specified-intervals) using RunJS.
:::
## Libraries
ToolJet allows you to internally utilize these libraries:
| Name | Documentation |
| ----------- | ----------- |
| Moment | [https://momentjs.com/docs/](https://momentjs.com/docs/) |
| Lodash | [https://lodash.com/docs/](https://lodash.com/docs/) |
| Axios | [https://axios-http.com/docs/intro](https://axios-http.com/docs/intro) |
:::info
Issues with writing custom JavaScript code? Ask in our [Slack Community](https://tooljet.com/slack).
:::