Last active
April 13, 2025 20:58
-
-
Save YamatoDX/4ac33a2c3a04603d5452c49abf6d4e28 to your computer and use it in GitHub Desktop.
Using Firebae v9 with NextJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # This is the first comment | |
| echo "First Argument is $1" | |
| echo "Second argument is $2" | |
| echo "All argument is done!" | |
| echo "Enter a number" | |
| read user_input # Going to take input from the user | |
| # This is the second comment | |
| if [ $user_input -gt 0 ]; then | |
| echo "Reacherd if statement" | |
| echo "$user_input is greater than 0" | |
| elif [ $user_input -eq 0 ]; then | |
| echo "user has entered zero" | |
| else | |
| echo "Reached else statement" | |
| echo "Reached the else statement" | |
| fi | |
| # This is the third comment | |
| my_array=("1" "2" "3" "4") # be careful about the space around the equal signs | |
| echo "my_array is ${my_array[@]}" | |
| for each in "${my_array[@]}"; do | |
| echo "each is $each" | |
| done | |
| function myFunction() { | |
| # echo "First arg is $1" | |
| # echo "Second arg is $2" | |
| sum=$(($1 + $2)) | |
| return $sum | |
| } | |
| # This is the fourth comment | |
| echo "Enter first number" | |
| read first_number | |
| echo "Enter second number" | |
| read second_number | |
| # clearning the log file | |
| myFunction $first_number $second_number | |
| final_result=$? # has some trouble while directly assigning the result to a variable | |
| echo "_result is $final_result" | |
| echo "First argument was $first_number" > logFile.txt # this overwrites the existing content of the file | |
| echo "Second argument was $second_number" >> logFile.txt # this is to append with the existing content of the file | |
| echo "Final Result was $final_result" >> logFile.txt | |
| # watch youtube "Learn Linux TV" channel | |
| # awk -F":" '{print $1}' logFile.txt # used awk while the delimiter ":", prints the first element | |
| # awk '{print $0}' logFile.txt # this will be printing the whole sentence | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // count-context.jsx | |
| import {createContext, useState} from "react" | |
| export const CountContext = createContext(null) | |
| export default function CountContextProvider({children}){ | |
| const [state, setState] = useState(0) | |
| return <CountContext.Provider value={{state, setState}}> | |
| {children} | |
| </CountContext.Provider> | |
| } | |
| // layout.jsx | |
| import CountContextProvider from "@/contexts/count-context" | |
| export default function RootLayout({children}){ | |
| return <CountContextProvider> | |
| <body> | |
| {children} | |
| </body> | |
| </CountContextProvider> | |
| } | |
| // first.jsx | |
| import {CountContext} from "@/contexts/count-context" | |
| import {useContext} from "react" | |
| export default functon First(){ | |
| const {state, setState} = useContext(CountContext) | |
| return <> | |
| Count: {state} | |
| <button onClick={() => setState(state + 1)}>Click to increase</button> | |
| </> | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "use client"; | |
| import { storage } from "@/config/firebaseApp"; | |
| import { ref, uploadBytes, getDownloadURL } from "firebase/storage"; | |
| import { useState } from "react"; | |
| export default function StorePractice() { | |
| const defaultState = { | |
| currentFile: null, | |
| name: "", | |
| fileURL: "", | |
| }; | |
| const [state, setState] = useState(defaultState); | |
| const uploadFileHandler = async () => { | |
| const { currentFile, name } = state; | |
| if (!currentFile || !name) return; | |
| const fileRef = ref(storage, `testing/${name}`); | |
| try { | |
| const snap = await uploadBytes(fileRef, currentFile); | |
| console.log("snap after uploading is", snap); | |
| const fileDownloadURL = await getDownloadURL(fileRef); | |
| console.log("file url is ", fileDownloadURL); | |
| alert("Uploading done"); | |
| setState({ | |
| ...state, | |
| fileURL: fileDownloadURL, | |
| }); | |
| } catch (err) { | |
| console.error("error message is", err.message); | |
| alert("Something went wrong"); | |
| } | |
| }; | |
| return ( | |
| <div> | |
| <input | |
| type="file" | |
| onChange={(e) => { | |
| const file = e.target.files[0]; | |
| const name = file.name; | |
| if (!file || !name) return; | |
| setState({ | |
| ...state, | |
| currentFile: file, | |
| name, | |
| }); | |
| }} | |
| /> | |
| <button | |
| onClick={() => { | |
| console.log("state is", state); | |
| }} | |
| > | |
| Click to see state | |
| </button> | |
| <button onClick={uploadFileHandler}>Upload the file</button> | |
| </div> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // this file is all about authentication | |
| import {auth} from "./firebaseApp" | |
| import { | |
| createUserWithEmailAndPassword, | |
| signOut, | |
| signInWithEmailAndPassword, | |
| onAuthStateChanged | |
| } from "firebase/auth"; | |
| const email = "your_email" | |
| const password = "your_password" | |
| await createUserWithEmailAndPassword(auth, email, password) | |
| await signInWithEmailAndPassword(auth, email, password) | |
| await signOut(auth) | |
| // listening for authentication changes in real-time | |
| onAuthStateChaned(auth, (cred) => { | |
| console.log("cred", cred); // this 'cred' contains lots of information including email and access token as well | |
| if(!cred){ | |
| // user has signed out | |
| // do something | |
| return; | |
| } | |
| // if you have reached here, meaning user has signed in or already logged in | |
| // so do something based on that information | |
| }) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import {initializeApp} from "firebase/app" | |
| import {getFirestore} from "firebase/firestore" | |
| import {getAuth} from "firebase/auth" | |
| const firebaseConfig = {} // get it from your project | |
| export const app = initializeApp(firebaseConfig); | |
| export const db = getFirestore(app) | |
| export const auth = getAuth(app) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import {query, where, orderBy, limit, collection, onSnapshot} from "firebase/firestore" | |
| import {db} from "./firebaseApp" | |
| const collectionRef = collection(db, "cities") | |
| const q = query(collectionRef, where("name", "==", "Shadman"), where("age", "<=", 30), orderBy("_id", "asc"), limit(20)) | |
| onSnapshot(q, (snaps) => { | |
| const allData = snaps.docs.map(each => each.data()) || [] | |
| console.log("allData is", allData); // this will be based on the queries that ran above | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import {db} from "./firebaseApp" | |
| import {collection, getDocs, doc, getDoc, deleteDoc, setDoc, | |
| onSnapshot} from "firebase/firestore" | |
| // getting all of the documents from a collection | |
| const collectionRef = collection(db, "products") | |
| const snaps = await getDocs(collectionRef) | |
| const collectionData = snaps.docs.map(each => each.data()) || [] | |
| // getting data of a single document | |
| // "01" is the document's id in the "products" collection | |
| const docRef = doc(db, "products", "01") | |
| const documentData = (await getDoc(docRef)).data() || {} | |
| // creating or updating a document | |
| const newData = { | |
| _id:"02", | |
| name:"Mobile", | |
| origin:"Malaysia" | |
| } | |
| const docRef = doc(db, "products", newData["_id"]) | |
| await setDoc(docRef, newData, {merge: true}) // this is for updating the values only | |
| await setDoc(docRef, newData, {merge: false}) // this will replace all of the existing data and will create a new one | |
| // deleting a document | |
| const docRef = doc(db, "products", newData["_id"]) | |
| await deleteDoc(docRef) | |
| // if we want to listen to changes real-time from firestore | |
| const collectionRef = collection(db, "cities") | |
| onSnapshot(collectionRef, (snapShots) => { | |
| const allData = snapShots.docs.map(each => each.data()) | |
| console.log("allData", allData) | |
| }) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // all about metadata | |
| // in a normal page | |
| export const metadata = { | |
| title: "sample title", | |
| descrition: "sample description" | |
| } | |
| // in a server component to dynamically generate meta data | |
| export const generateMetata = async ({params}) => { | |
| // params is the data that can be used in dynamic routing | |
| // params.postId is the data in ./app/somePage/[postId].jsx | |
| const data = someData // someData is achieved from some async call | |
| return { | |
| title: data?.title ?? "", | |
| description: data?.description ?? "" | |
| } | |
| } | |
| // to change favicon.ico needs to be replaced at ./app/favicon.ico | |
| // to change the social media preview image replace/create image at ./app/opengraph-image.png | |
| // some useful links | |
| // socialsharepreview.com | |
| // realfavicongenerator.net | |
| // dummyjson.com | |
| // to dynamically generate titles in child pages | |
| // layout.jsx | |
| export const metadata = { | |
| title:{ | |
| default:"", | |
| template:"here - %s" // %s is the title of the child page | |
| }, | |
| description: "some description" | |
| } | |
| // dynamic routing | |
| // if the page is statically rendered, SEO will better crawl it | |
| // ./app/dynamic/[postId].jx | |
| export const generateStaticParams = async () => { | |
| const allIds = [1,2,3,4] | |
| return allIds.map(each => ({ | |
| postId: each.toString() // must a string value | |
| })) | |
| } | |
| const fetchCurrentData = async (id) => { | |
| const url = `https://dummyjson.com/posts/${id}` | |
| const response = await (await fetch(url)).json() | |
| return response; | |
| } | |
| export default function DetailsPage({params}){ | |
| const currentData = fetchCurrentData(params.postId) | |
| return <div>{JSON.stringify(currentData)}</div> | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| echo "First Shell Script running" | |
| echo "I am going to product multiplication table" | |
| echo | |
| echo "Enter the range start" | |
| read start_range | |
| echo "Enter the range final" | |
| read final_range | |
| # numbers=({1..10}) | |
| numbers=($(seq $start_range $final_range)) | |
| echo "Numbers array is ${numbers[@]}" | |
| echo > logFile.txt | |
| for i in ${numbers[@]}; do | |
| for j in ${numbers[@]}; do | |
| if (( j % 2 == 0 )); then | |
| continue | |
| fi | |
| current_value=$((i * j)) | |
| echo "$i X $j = $current_value" >> logFile.txt | |
| done | |
| echo >> logFile.txt | |
| done |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useEffect } from "react"; | |
| import useSWR from "swr"; | |
| import { | |
| collection, | |
| query, | |
| where, | |
| orderBy, | |
| limit, | |
| onSnapshot, | |
| } from "firebase/firestore"; | |
| const useCollection = (db, collectionName, options = {}) => { | |
| const { | |
| limit: limitOption, | |
| orderBy: orderByOption, | |
| where: whereOptions = [], | |
| subscribe = true, | |
| } = options; | |
| const collectionKey = JSON.stringify({ | |
| collectionName, | |
| limitOption, | |
| orderByOption, | |
| whereOptions, | |
| }); | |
| const { data, error, mutate } = useSWR(collectionKey, () => null); | |
| useEffect(() => { | |
| if (!subscribe || !db || !collectionName) { | |
| return; | |
| } | |
| let unsubscribe; | |
| const fetchData = async () => { | |
| try { | |
| // Validate collection name | |
| if ( | |
| typeof collectionName !== "string" || | |
| collectionName.trim() === "" | |
| ) { | |
| throw new Error("Invalid collection name"); | |
| } | |
| const collectionRef = collection(db, collectionName); | |
| const queryConstraints = []; | |
| // Safely add where clauses | |
| if (Array.isArray(whereOptions)) { | |
| whereOptions.forEach((whereClause) => { | |
| if (Array.isArray(whereClause) && whereClause.length === 3) { | |
| queryConstraints.push(where(...whereClause)); | |
| } | |
| }); | |
| } | |
| // Safely add orderBy | |
| if (Array.isArray(orderByOption) && orderByOption.length >= 1) { | |
| queryConstraints.push(orderBy(...orderByOption)); | |
| } | |
| // Safely add limit | |
| if (typeof limitOption === "number" && limitOption > 0) { | |
| queryConstraints.push(limit(limitOption)); | |
| } | |
| const q = query(collectionRef, ...queryConstraints); | |
| unsubscribe = onSnapshot( | |
| q, | |
| (querySnapshot) => { | |
| const results = []; | |
| querySnapshot.forEach((doc) => { | |
| results.push({ | |
| id: doc.id, | |
| ...doc.data(), | |
| }); | |
| }); | |
| mutate(results, false); | |
| }, | |
| (err) => { | |
| console.error("Firestore snapshot error:", err); | |
| mutate(undefined, false); | |
| } | |
| ); | |
| } catch (err) { | |
| console.error("Error setting up collection listener:", err); | |
| mutate(undefined, false); | |
| } | |
| }; | |
| fetchData(); | |
| return () => { | |
| if (unsubscribe && typeof unsubscribe === "function") { | |
| unsubscribe(); | |
| } | |
| }; | |
| }, [ | |
| db, | |
| collectionName, | |
| limitOption, | |
| orderByOption, | |
| whereOptions, | |
| subscribe, | |
| mutate, | |
| ]); | |
| return { | |
| data: data || [], | |
| isLoading: !error && !data, | |
| isError: error, | |
| error, | |
| }; | |
| }; | |
| export default useCollection; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useEffect, useState } from "react"; | |
| import { | |
| onSnapshot, | |
| collection, | |
| query, | |
| where, | |
| limit, | |
| orderBy, | |
| } from "firebase/firestore"; | |
| import { db } from "@/config/firebaseApp"; | |
| export default function useCustomCollection(collectionName, options = {}) { | |
| const [state, setState] = useState([]); | |
| const [loading, setLoading] = useState(false); | |
| const { | |
| where: whereOptions = [], | |
| limit: limitValue = undefined, | |
| orderBy: orderByOptions = [], | |
| } = options; | |
| useEffect(() => { | |
| const collectionRef = collection(db, collectionName); | |
| let queryConstraints = []; | |
| if (whereOptions.length) { | |
| whereOptions.forEach((each) => queryConstraints.push(where(...each))); | |
| } | |
| if (limitValue) { | |
| queryConstraints.push(limit(limitValue)); | |
| } | |
| if (orderByOptions.length) { | |
| queryConstraints.push(orderBy(...orderByOptions)); | |
| } | |
| const q = query(collectionRef, ...queryConstraints); | |
| setLoading(true); | |
| const unsubscribe = onSnapshot(q, (snapshots) => { | |
| const allData = snapshots.docs.map((each) => each.data()) || []; | |
| setState(allData); | |
| setLoading(false); | |
| }); | |
| return () => unsubscribe(); | |
| }, []); | |
| return { | |
| data: state, | |
| isLoading: loading, | |
| }; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useEffect, useState, useCallback } from "react"; | |
| import { onSnapshot, doc, setDoc } from "firebase/firestore"; | |
| import { db } from "@/config/firebaseApp"; | |
| export default function useCustomDocument(docLocation, options = {}) { | |
| const { listen = true } = options; | |
| const [data, setData] = useState({}); | |
| const [loading, setLoading] = useState(false); | |
| const [error, setError] = useState({}); | |
| const set = useCallback( | |
| async (newData, options) => { | |
| if ( | |
| typeof docLocation === "string" && | |
| docLocation.length && | |
| docLocation.includes("/") | |
| ) { | |
| const [collectionName, docId] = docLocation.split("/"); | |
| if (!collectionName || !docId) return; | |
| setLoading(true); | |
| try { | |
| const docRef = doc(db, collectionName, docId); | |
| if (options?.merge) { | |
| await setDoc(docRef, newData, { merge: true }); // updating the document | |
| } else { | |
| await setDoc(docRef, newData, { merge: false }); // creating the document fresh | |
| } | |
| } catch (err) { | |
| setError(err); | |
| } finally { | |
| setLoading(false); | |
| } | |
| } | |
| }, | |
| [docLocation] | |
| ); | |
| useEffect(() => { | |
| if ( | |
| typeof docLocation === "string" && | |
| docLocation.length && | |
| docLocation.includes("/") | |
| ) { | |
| setLoading(true); | |
| const [collectionName, docId] = docLocation.split("/"); | |
| if (!collectionName || !docId) return; | |
| const docRef = doc(db, collectionName, docId); | |
| const unsubscribe = onSnapshot(docRef, (snap) => { | |
| setData(snap.data()); | |
| setLoading(false); | |
| }); | |
| return () => unsubscribe(); | |
| } | |
| }, []); | |
| return { | |
| data, | |
| loading, | |
| set, | |
| error, | |
| }; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { auth } from "@/config/firebaseApp"; | |
| import { onAuthStateChanged } from "firebase/auth"; | |
| import { useEffect, useState } from "react"; | |
| export default function useUserProfile() { | |
| const [user, setUser] = useState({}); | |
| const [loading, setLoading] = useState(false); | |
| useEffect(() => { | |
| const unsubscribe = onAuthStateChanged(auth, (cred) => { | |
| setLoading(true); | |
| if (!cred) { | |
| setUser({}); | |
| setLoading(false); | |
| return; | |
| } | |
| setUser(cred); | |
| setLoading(false); | |
| }); | |
| return () => unsubscribe(); | |
| }, []); | |
| return { | |
| user, | |
| loading, | |
| }; | |
| } |
Comments are disabled for this gist.