3

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]

RS Motors
  • 85
  • 1
  • 6

3 Answers3

5

You can use the following:

https://www.npmjs.com/package/react-native-uuid

npm install react-native-uuid

import uuid from 'react-native-uuid';
uuid.v4(); // ⇨ '11edc52b-2918-4d71-9058-f7285e29d894'

If you are not able to use other libraries in your project see the following related question:
How to create a GUID / UUID

SKeney
  • 1,449
  • 2
  • 7
  • 23
1
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());
}
1

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

Felipe Chernicharo
  • 2,092
  • 1
  • 16
  • 22