zahra zamani
zahra zamani

Reputation: 1375

How can I create a unique ID

I have a grid to which I can add or remove data For add I have this method

  handelAddValueTransactionInput() {
                let valueTransaction = this.state.valueTransaction;
                valueTransaction.push({ id: valueTransaction.length + 1,Value:this.state.valueTransactionInput });

                this.setState({ valueTransaction, valueTransactionInput: '' })

            }
          

for delete:

 deleteValueTransaction(data) {

        let indexOfDeleted = -1;
        let valueTransaction = this.state.valueTransaction;
        this.state.valueTransaction.forEach((item, index) => {
            if (item.id === data.id) {

                indexOfDeleted = index;

            }
        })
        valueTransaction.splice(indexOfDeleted, 1);

        this.setState({

            valueTransaction: valueTransaction

        });
    }

My problem is that when I have 3 data and I delete the second one and add one data twice .. the data that is added creates the same ID as the previous one

How can I create a unique ID for each?

Upvotes: 0

Views: 78

Answers (3)

guicontat
guicontat

Reputation: 105

You can use UUID

function create_UUID() {
  var dt = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (dt + Math.random() * 16) % 16 | 0;
    dt = Math.floor(dt / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}
for (let i = 0; i < 10; i++)
  console.log(create_UUID());

Upvotes: 3

Alexander Smirnov
Alexander Smirnov

Reputation: 408

For ids with length < 15 you can use following formula and combine it for large strings.

getRandomString = (length) => {
    return Math.random().toString(36).substring(2, length + 2)
}

Upvotes: 1

Shani Kehati
Shani Kehati

Reputation: 548

If you want a random string, search for a "random string generator in JavaScript", I don't have it open now but there is such a function on another stack overflow question. One of the answers gives a nice function that returns a random string

Upvotes: 1

Related Questions