Category: JS Objects
Updated

Generating and Incrementing Unique Ids

Issue

This article explains how to generate and increment unique IDs. In this example, the IDs are triggered on button click and start with REF followed by numbers that increase by 1 each time.

Resolution

To generate unique IDs with a specific pattern using a button click, the first step is to initialize the ID value. This can be done using the storeValue() function and setting it to run on page load. These are the steps:

  1. Create a JS Object with an init function.
  2. In this function, initialize the ID value and set it to run on page load. To generate the first value, you can install the UUID library and generate a unique ID using UUID.generate().
  3. Then, every time you need to generate a new ID, you can run a method like the one below and run it in the onClick event of a button.
getNewId: () => {
  let id = appsmith.store.uniqueId + 1;
  storeValue('uniqueId', id);
  return `REF${id}`
}

4. If you need to persist the ID across different sessions, then you can store its most recent value in a datasource. You could then load the value on page load to always stay up to date.