ToolJet/docs/versioned_docs/version-2.27.0/data-sources/custom-js.md
2024-04-16 15:27:39 +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).
:::