How to generate unique id in react native

Viewed 10549

I am new to react native and working on my first project in expo. I am trying to generate unique id for every order that is being placed by the user, below is what I have tried

 const orderId = () => {
    var S4 = () => {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (
      S4() +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      S4() +
      S4()
    );
  };
  console.log(orderId);

what I am getting in terminal is [Function orderId]

4 Answers
function guidGenerator(){
    vary S4 = function(){
        return (((1+Math.random())*0x10000)|0).to String(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

Ran into this problem today....tried to use nanoid in React Native and Baaam...
Well then...So why not write our own simple solution? This one does the job just fine :)

export function generateUUID(digits) {
    let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXZ';
    let uuid = [];
    for (let i = 0; i < digits; i++) {
        uuid.push(str[Math.floor(Math.random() * str.length)]);
    }
    return uuid.join('');
}

generateUUID(10) // 7ABLSma6F6
generateUUID(32) // FCGQ91Q5r2y3PkkPFuHhFh9JusMMDFwR

Related