Skip to main content

Lesson 2 - 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.

By the end of this lesson, you will learn how to:

  • Create and configure the JS module
  • Integrate and execute the module in your app

Create JS modules

  1. Open the ProductUtils package created in lesson 1.

  2. Click the + icon in the top-left corner and select JS Module. With JS Modules you can create datasource queries and JS objects inside the module.

  3. Rename the module to formatDate. The Main JS object represents the code for the JS module.

  4. 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);
},
};
  1. Publish the JS Module.

Integrate modules into your App

Follow these steps to access its data in any application:

  1. Open the App created in Lesson 1.

  2. Select the JS tab on the Entity Explorer.

  3. Click the + New JS object and select the formatDate JS module.

  4. From the UI tab, select Table widget and open the updated column by clicking ⚙️ gear icon.

  5. 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.

info

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.

See Also