firebase-9 with javascript (net-ninja) :
Tags: webdev, javascript, firebase, coding
Published: 2022-11-30 07:00:45

## Folder Structure :-

![Folder Structure Output Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yjmwn8okakbpy3p660x1.png)

## Index.html Code :

``` html
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title> FireBase 9 </title>
</head>

<body>
  <h1> Getting Started with Firebase 9 </h1>

  <h1 id="load"> loading </h1>

  <hr>

  <form action="" class="add">
    <h2> Add Data </h2>
    <label for="author">Author</label>
    <input type="text" id="author">

    <label for="title">Title</label>
    <input type="text" id="title">

    <button type="submit">Submit</button>
  </form>

  <form action="" class="delete">
    <h2> Delete Data </h2>
    <label for="delete"> Delete </label>
    <input type="text" id="delete">

    <button type="submit">delete</button>
  </form>

  <form action="" class="update">
    <h2> Update Data </h2>
    <label for="">Document id: </label>
    <input type="text" name="id" required>

    <input type="submit" value="update a book">
  </form>


  <h2> Firebase Auth </h2>

  <h2> Signup </h2>
  <form action="" class="signup">
    email <input type="text" name="email">
    password <input type="password" name="password" id="">
    <input type="submit" value="submit">
  </form>


  <h2> login </h2>
  <form action="" class="login">
    email <input type="text" name="email">
    password <input type="password" name="password" id="">
    <input type="submit" value="login">
  </form>

  <button class="signout">logout</button>

  <h2> UnSubscribe </h2>
  <button class="unsub"> UnSubscribe from db/auth Changes </button>

  <script src="bundle.js"></script>
</body>

</html>
```

## index.js code

``` javascript
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";

import {
  getFirestore, collection,
  getDocs, addDoc, doc, deleteDoc,
  onSnapshot,
  query, where,
  orderBy, limit,
  serverTimestamp,
  getDoc,
  updateDoc
} from "firebase/firestore";


import {
  getAuth, createUserWithEmailAndPassword,
  signOut, signInWithEmailAndPassword,
  onAuthStateChanged
} from "firebase/auth";


const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};


// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

// init firebase services
const db = getFirestore(app);

// Initialize Firebase Authentication and get a reference to the service
const auth = getAuth(app);

// collection ref
const colRef = collection(db, 'books');

// get collection data
// function getData() {

//   getDocs(colRef)
//     .then((snapshot) => {
//       console.log('1', snapshot.docs)

//       let books = [];
//       document.getElementById("load").innerHTML = "";
//       snapshot.docs.forEach((item) => {
//         books.push({ ...item.data(), id: item.id });
//         console.log(item.data());

//         document.getElementById("load").innerHTML += `${item.data().title} - ${item.data().author} - ${item.id} <br>`
//       })

//       console.table(books);
//     })
//     .catch((err) => {
//       console.log('err', err.message);
//       document.getElementById("load").innerHTML += `${err.message}`
//     })

// }
// getData();

// queries 
const q = query(colRef, where("author", "==", "Aksh"));

// Orderby and limit 
// const q1 = query(colRef, where("author", "!=", "Aksh"), orderBy('author', 'asc'));
const q1 = query(colRef, orderBy('createdAt'));

// get real time collection data
const unsubCol = onSnapshot(q1, (snapshot) => {
  let books = [];
  document.getElementById("load").innerHTML = "";
  snapshot.docs.forEach((item) => {
    books.push({ ...item.data(), id: item.id });
    console.log(item.data());

    document.getElementById("load").innerHTML += `${item.data().title} - ${item.data().author} - ${item.id} <br>`
  })
})


const addBookForm = document.querySelector('.add');
addBookForm.addEventListener('submit', (e) => {
  e.preventDefault();
  console.log('add');

  addDoc(colRef, {
    author: addBookForm.author.value,
    title: addBookForm.title.value,
    createdAt: serverTimestamp()
  })
    .then(() => {
      addBookForm.reset();
    })
    .catch((error) => {
      alert('Some Error Occured.')
    })

  getData();
})


const deleteBookForm = document.querySelector('.delete');
deleteBookForm.addEventListener('submit', (e) => {
  e.preventDefault();
  console.log('delete');

  const docRef = doc(db, 'books', deleteBookForm.delete.value);
  deleteDoc(docRef)
    .then(() => {
      deleteBookForm.reset();
    })
    .catch((error) => {
      alert('Some Error Occured.')
    })

  getData();
})

// get single documents
const docRef = doc(db, "books", "PmKxAwW9SX9a6cCcurTG");
console.log(11);
getDoc(docRef)
  .then((snapshot) => {
    console.log('aksh', snapshot.data(), snapshot.id)
  })
  .catch((error) => {
    alert(`aksh - ${error.message}`)
  })

const unsubDoc = onSnapshot(docRef, (doc) => {
  console.log(doc.data(), doc.id);
})


// update document 
const updateBookForm = document.querySelector('.update');
updateBookForm.addEventListener('submit', (e) => {
  e.preventDefault();

  const docRef = doc(db, 'books', updateBookForm.id.value)
  const update = updateDoc(docRef, { title: 'updated title' })
    .then((snapshot) => {
      updateBookForm.reset();
    })
})


// signing users up
const signupForm = document.querySelector('.signup')
signupForm.addEventListener('submit', (e) => {
  e.preventDefault();

  createUserWithEmailAndPassword(auth, signupForm.email.value, signupForm.password.value)
    .then((userCredential) => {
      // Signed in 
      const user = userCredential.user;
      console.log(user);
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      console.error(errorCode, errorMessage)
    });

})

// login user 
const loginForm = document.querySelector('.login')
loginForm.addEventListener('submit', (e) => {
  e.preventDefault();

  signInWithEmailAndPassword(auth, loginForm.email.value, loginForm.password.value)
    .then((userCredential) => {
      // Signed in 
      const user = userCredential.user;
      console.log(user);
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      console.error(errorCode, errorMessage)
    });

})


// login user 
const signoutForm = document.querySelector('.signout')
signoutForm.addEventListener('click', (e) => {
  e.preventDefault();

  signOut(auth)
    .then(() => {
      console.log('signout');
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      console.error(errorCode, errorMessage)
    });

})


// subscribing to auth changes 
const unsubAuth = onAuthStateChanged(auth, (user) => {
  console.log('user status changed', user.email);
  // if (user) {
  //   const uid = user.uid;
  //   // ...
  // } else {
  //   // User is signed out
  //   // ...
  // }
});

const unsubscribe = document.addEventListener('.unsub');
unsubscribe.addEventListener('click', () => {
  console.log('un subscribing')
  unsubCol();
  unsubDoc();
  unsubAuth();
})
```

## webpack.config.js

``` javascript
const path = require('path');

module.exports = {
    mode: 'development',
    // The entry point file described above
    entry: './src/index.js',
    // The location of the build folder described above
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    watch: true
};
```


Thank You.
You can follow us on:
[Youtube ](https://www.youtube.com/c/ULTIMATEPROGRAMMING)
[Instagram](https://www.instagram.com/full_stack_web_developer1/)