CUID package to generate unique identifiers in JavaScript apps

In the last blog post, we have generated sample testing dataset using faker package. We used the array index value for the ID.

Array index value as ID will work if the data is static. But if you add/remove data, then it will be tricky to maintain.

For example, you need to insert a new item at array index 18 in a 100 items array. Then the array length will become 101 and there will be two id with the value 18.

An ID should be unique. There are ways to create unique IDs. There are NPM packages to take off the computation from us, one such package is CUID. You can install it by,

npm install cuid

Let's generate a unique ID,

import cuid from 'cuid';

// Generate a random Unique ID
console.log(cuid()); // ckidiqema00003g68g7qr1u82

Now, let's replace the index value as ID in our previous blog post example. This was the code of sample data generated using faker package,

// Create sample data
const createFaqs = (n = 10) => {
  const faqs = Array(n)
    .fill({}) // Create `n` items and fill empty object
    .map((_, id) => ({
      id, // array index value as the unique ID
      question: faker.lorem.words(),
      answer: faker.lorem.paragraphs(),
      author: {
        name: faker.name.findName(),
        email: faker.internet.email(),
        website: faker.internet.url()
      }
    }));

  return faqs;
};

Now, instead of index value, you can replace the line with,

{
    id: cuid(),
}

The complete function code after the update will be,

const createFaqs = (n = 10) => {
  const faqs = Array(n)
    .fill({}) // Create `n` items and fill empty object
    .map(() => ({
      id: cuid(), //
      question: faker.lorem.words(),
      answer: faker.lorem.paragraphs(),
      author: {
        name: faker.name.findName(),
        email: faker.internet.email(),
        website: faker.internet.url()
      }
    }));

  return faqs;
};

You can play around with the complete code example here,

You can read more about the package here.