JS modules
A JavaScript module serves as a reusable code unit, encapsulating specific functionalities to promote an organized code structure.
To learn JS modules in Appsmith, you'll be building a function that formats dates into DD/MM/YYYY format. This function will be used to format the product data obtained from the query module in lesson 1.
You'll learn how to reuse JavaScript code to format dates within your applications. By the end of this tutorial, you will learn:
- 🔧 Basics: Learn how to create and configure the JS module
- 🔄 Dynamic Data: Learn how to pass data between the app and JS module
- ♻️ Reusability: Discover how to reuse the JS module within applications
Prerequisites
Before you start, make sure you have the following:
- A self-hosted instance of Appsmith with a paid subscription. Refer to the Appsmith installation guides for detailed instructions on setting up your Appsmith instance.
- If you are new to Appsmith, see Tutorial - Basics.
Create JS modules
-
Open an existing package or create a new one from the top-right corner of your workspace.
-
Click the + icon in the top-left corner and select JS Module.
-
Rename the module to formatDate.
-
In the Main JS Object, delete the auto-generated code and add the below code to it:
To pass data from the app to JS modules, you can pass it by calling the respective function with the necessary parameters, like formatDDMMYYYY('2023-03-08T09:45:15Z')
.
The following code takes a parameter dateString
and uses the toLocalString()
method of the date object to convert the given date into the DD/MM/YYYY
format.
export default {
// Function to format a date string as 'DD/MM/YYYY'
formatDDMMYYYY: (dateString = '2023-03-08T09:45:15Z') => {
const date = new Date(dateString);
const options = {
day: '2-digit',
month: '2-digit',
year: 'numeric',
};
return date.toLocaleString('en-GB', options);
},
};
- Publish the JS Module.
Integrate modules into your App
Follow these steps to access its data in any application:
-
Open the App created in Lesson 1.
-
Select the JS tab on the Entity Explorer.
-
Click the + New JS object and select the formatDate JS module.
-
From the UI tab, select Table widget and open the
updated
column by clicking ⚙️ gear icon. -
In the Computed value property, add:
{{formatDate_1.formatDDMMYYYY(currentRow["updated"])}}
The formatDate_1
represents the module instance, and the number corresponds to the order in which the module was added.
This code formats all updated
column data into the DD/MM/YYYY
format for each row in the data array.
When you update and publish a package, these modifications automatically apply in the edit mode of the app. However, the live (deployed) version of the app remains unchanged until you redeploy the app.