Home > Enterprise >  Firebase Database unique id per save
Firebase Database unique id per save

Time:12-09

My code below works PERFECT, but I have one issue.

        set(ref(db, "People/"  ?????),{
            Email: email,    
            Password: password,
            })
            .then(()=>{
                console.log('Success');
            })
            .catch((error)=>{
                alert(error);
            });
        delay(1000).then(() => window.location.href='https://thecoletimes.ml/home');
      function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}
    })
    .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        alert('Your request was rejected because either your email is already in use, or your email is invalid. Please double check your info.');
    });

When I am saving the data, I want each person to have a unique id as the string.

I have though about math.random

But then if people got the same number, they would have the same number. I need each person to have a unique string.

I am using html and javascript.

CodePudding user response:

you can try uuid, which I use in my production. Check the npm docs however for more option.. As for the function in the code you can put it in a helper function module and use it all over your code as centralized location, in case you want to generate an id in more than one place.

// uuid
import { v4 as uuidv4 } from 'uuid';

export const generateId = () => {
  const id = uuidv4();
  return id ;
};

CodePudding user response:

If you want to generate a unique ID, it's recommended to use Firestore's built-in addDoc function instead of setDoc:

addDoc(ref(db, "People"),{
    Email: email,    
    Password: password,
    })
    .then(()=>{
        console.log('Success');
    })
    .catch((error)=>{
        alert(error);
    });

Also see the Firebase documentation on adding a document.

  • Related