<htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title> FireBase 9 </title></head><body><h1> Getting Started with Firebase 9 </h1><h1id="load"> loading </h1><hr><formaction=""class="add"><h2> Add Data </h2><labelfor="author">Author</label><inputtype="text"id="author"><labelfor="title">Title</label><inputtype="text"id="title"><buttontype="submit">Submit</button></form><formaction=""class="delete"><h2> Delete Data </h2><labelfor="delete"> Delete </label><inputtype="text"id="delete"><buttontype="submit">delete</button></form><formaction=""class="update"><h2> Update Data </h2><labelfor="">Document id: </label><inputtype="text"name="id"required><inputtype="submit"value="update a book"></form><h2> Firebase Auth </h2><h2> Signup </h2><formaction=""class="signup">
email <inputtype="text"name="email">
password <inputtype="password"name="password"id=""><inputtype="submit"value="submit"></form><h2> login </h2><formaction=""class="login">
email <inputtype="text"name="email">
password <inputtype="password"name="password"id=""><inputtype="submit"value="login"></form><buttonclass="signout">logout</button><h2> UnSubscribe </h2><buttonclass="unsub"> UnSubscribe from db/auth Changes </button><script src="bundle.js"></script></body></html>
index.js code
// Import the functions you need from the SDKs you needimport{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";constfirebaseConfig={apiKey:"",authDomain:"",projectId:"",storageBucket:"",messagingSenderId:"",appId:"",measurementId:""};// Initialize Firebaseconstapp=initializeApp(firebaseConfig);constanalytics=getAnalytics(app);// init firebase servicesconstdb=getFirestore(app);// Initialize Firebase Authentication and get a reference to the serviceconstauth=getAuth(app);// collection refconstcolRef=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 constq=query(colRef,where("author","==","Aksh"));// Orderby and limit // const q1 = query(colRef, where("author", "!=", "Aksh"), orderBy('author', 'asc'));constq1=query(colRef,orderBy('createdAt'));// get real time collection dataconstunsubCol=onSnapshot(q1,(snapshot)=>{letbooks=[];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>`})})constaddBookForm=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();})constdeleteBookForm=document.querySelector('.delete');deleteBookForm.addEventListener('submit',(e)=>{e.preventDefault();console.log('delete');constdocRef=doc(db,'books',deleteBookForm.delete.value);deleteDoc(docRef).then(()=>{deleteBookForm.reset();}).catch((error)=>{alert('Some Error Occured.')})getData();})// get single documentsconstdocRef=doc(db,"books","PmKxAwW9SX9a6cCcurTG");console.log(11);getDoc(docRef).then((snapshot)=>{console.log('aksh',snapshot.data(),snapshot.id)}).catch((error)=>{alert(`aksh - ${error.message}`)})constunsubDoc=onSnapshot(docRef,(doc)=>{console.log(doc.data(),doc.id);})// update document constupdateBookForm=document.querySelector('.update');updateBookForm.addEventListener('submit',(e)=>{e.preventDefault();constdocRef=doc(db,'books',updateBookForm.id.value)constupdate=updateDoc(docRef,{title:'updated title'}).then((snapshot)=>{updateBookForm.reset();})})// signing users upconstsignupForm=document.querySelector('.signup')signupForm.addEventListener('submit',(e)=>{e.preventDefault();createUserWithEmailAndPassword(auth,signupForm.email.value,signupForm.password.value).then((userCredential)=>{// Signed in constuser=userCredential.user;console.log(user);}).catch((error)=>{consterrorCode=error.code;consterrorMessage=error.message;console.error(errorCode,errorMessage)});})// login user constloginForm=document.querySelector('.login')loginForm.addEventListener('submit',(e)=>{e.preventDefault();signInWithEmailAndPassword(auth,loginForm.email.value,loginForm.password.value).then((userCredential)=>{// Signed in constuser=userCredential.user;console.log(user);}).catch((error)=>{consterrorCode=error.code;consterrorMessage=error.message;console.error(errorCode,errorMessage)});})// login user constsignoutForm=document.querySelector('.signout')signoutForm.addEventListener('click',(e)=>{e.preventDefault();signOut(auth).then(()=>{console.log('signout');}).catch((error)=>{consterrorCode=error.code;consterrorMessage=error.message;console.error(errorCode,errorMessage)});})// subscribing to auth changes constunsubAuth=onAuthStateChanged(auth,(user)=>{console.log('user status changed',user.email);// if (user) {// const uid = user.uid;// // ...// } else {// // User is signed out// // ...// }});constunsubscribe=document.addEventListener('.unsub');unsubscribe.addEventListener('click',()=>{console.log('un subscribing')unsubCol();unsubDoc();unsubAuth();})
webpack.config.js
constpath=require('path');module.exports={mode:'development',// The entry point file described aboveentry:'./src/index.js',// The location of the build folder described aboveoutput:{path:path.resolve(__dirname,'dist'),filename:'bundle.js'},watch:true};
Top comments (0)