Skip to content

Instantly share code, notes, and snippets.

@bpiroman
Last active May 2, 2024 13:14
Show Gist options
  • Save bpiroman/aa0bdd96cadad793daf5150f612c9c1f to your computer and use it in GitHub Desktop.
Save bpiroman/aa0bdd96cadad793daf5150f612c9c1f to your computer and use it in GitHub Desktop.
firebase v9 reference

Firebase V9

1.0 Configuration

2.0 Initialisation

3.0 Authentication

3.1 Create User

try {
  // Create user with email and password
  const userCredential = await createUserWithEmailAndPassword(auth, email, password);
  // Signed up
  const user = userCredential.user;

  // Update user profile with name and surname
  await updateProfile(auth.currentUser, {
    displayName: `${name} ${surname}`,
  });

  // Additional actions after sign-up if needed
  window.location.replace("http://"+host+"/dashboard");
} catch (error) {
  // Handle sign-up errors
  const errorCode = error.code;
  const errorMessage = error.message;
  console.error("Sign-up error:", errorMessage);
}

3.2 Sign in with Email / Password

try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    // Signed in
    const user = userCredential.user;
    // Additional logic here if needed
    console.log("User signed in successfully.");
    window.location.replace("http://"+host+"/dashboard");
} catch (error) {
    // Handle sign-in errors
    const errorCode = error.code;
    const errorMessage = error.message;
    console.error("Sign-in error:", errorMessage);
    throw error;
}

3.3 Sign Out

try {
    await signOut(auth);
    console.log('sign out success!');
    window.location.replace("http://"+host+"/login");
} catch (error) {
    // An error happened.
    console.error("Sign-out error:", error);
}

3.4 Auth State Listener

onAuthStateChanged(auth, function(user) {
  if (user) {
      // User is signed in
      console.log('User is signed in');
      if (window.location.pathname === '/dashboard') {
          // If the current page is the dashboard, stay on the dashboard
          return;
      } else {
          // Redirect to the dashboard
          window.location.replace("http://"+host+"/dashboard");
      }
  } else {
      // No user is signed in
      console.log('No user is signed in');
      if (window.location.pathname === '/login' || window.location.pathname === '/signup') {
          // If the current page is the login or signup page, stay there
          return;
      } else {
          // Redirect to the login page
          window.location.replace("http://"+host+"/login");
      }
  }
});

4.0 Firestore

4.1 Add / Set Document

// Add a document to a collection (with an auto assigned doc ID)
const uid = await getUserUID();
await addDoc(collection(db, "some-collection"), {
    mapName: "Los Angeles"
});

4.2 Update / Delete Document

const documentRef = doc(firestore, "some-collection", "some-doc-name");
const mergeExistingDoc = async () => {
  try {
    await setDoc(
      documentRef,
      {
        contents: "some-data",
      },
      { merge: true }
    );
    console.log("Updated/merged!");
  } catch (error) {
    console.error(error);
  }
};

4.3 Sever Timestamps and incrementing counters

4.4 Batch Operations

4.5 Querying and Reading Data

import {query, where, collection} from "firebase/firestore";

// Initialize auth && firestore with the 'firebaseApp' property
const db = getFirestore(app);

// Collection/doc ref
const collectionRef = collection(db, "some-collection");

// Use a query with collection listener
const collectionListener = (collection) => {
const collectionQuery = query(collectionRef, where("some-data", "==", true));

onSnapshot(collectionQuery, (querySnapshot) => {
    let dataArray = [];
    querySnapshot.forEach((doc) => {
    dataArray.push(doc.data());
    });
    dataArray.map((d) => console.log(d));
});
};

next

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment