Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Firebase v10 #32

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions components/HeartButton.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { firestore, auth, increment } from '@lib/firebase';
import { firestore, auth } from '@lib/firebase';
import { collection, doc, increment, writeBatch } from 'firebase/firestore';
import { useDocument } from 'react-firebase-hooks/firestore';

// Allows user to heart or like a post
export default function Heart({ postRef }) {
// Listen to heart document for currently logged in user
const heartRef = postRef.collection('hearts').doc(auth.currentUser.uid);
const heartRef = doc(collection(postRef, 'hearts'), auth.currentUser.uid);
const [heartDoc] = useDocument(heartRef);

// Create a user-to-post relationship
const addHeart = async () => {
const uid = auth.currentUser.uid;
const batch = firestore.batch();
const batch = writeBatch(firestore);

batch.update(postRef, { heartCount: increment(1) });
batch.set(heartRef, { uid });
Expand All @@ -20,15 +21,15 @@ export default function Heart({ postRef }) {

// Remove a user-to-post relationship
const removeHeart = async () => {
const batch = firestore.batch();
const batch = writeBatch(firestore);

batch.update(postRef, { heartCount: increment(-1) });
batch.delete(heartRef);

await batch.commit();
};

return heartDoc?.exists ? (
return heartDoc?.exists() ? (
<button onClick={removeHeart}>💔 Unheart</button>
) : (
<button onClick={addHeart}>💗 Heart</button>
Expand Down
41 changes: 25 additions & 16 deletions components/ImageUploader.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState } from 'react';
import { auth, storage, STATE_CHANGED } from '@lib/firebase';
import { auth, storage } from '@lib/firebase';
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";
import Loader from './Loader';

// Uploads images to Firebase Storage
Expand All @@ -15,25 +16,33 @@ export default function ImageUploader() {
const extension = file.type.split('/')[1];

// Makes reference to the storage bucket location
const ref = storage.ref(`uploads/${auth.currentUser.uid}/${Date.now()}.${extension}`);
const fileRef = ref( storage, `uploads/${auth.currentUser.uid}/${Date.now()}.${extension}` );
setUploading(true);

// Starts the upload
const task = ref.put(file);

// Listen to updates to upload task
task.on(STATE_CHANGED, (snapshot) => {
const pct = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0);
setProgress(pct);
});

// Get downloadURL AFTER task resolves (Note: this is not a native Promise)
task
.then((d) => ref.getDownloadURL())
.then((url) => {
setDownloadURL(url);
const task = uploadBytesResumable(fileRef, file);

// Get downloadURL AFTER task resolves
task.on(
"state_changed",
(snapshot) => {
const pct = (
(snapshot.bytesTransferred / snapshot.totalBytes) *
100
).toFixed(0);
setProgress(Number(pct));
},
(error) => {
// TODO handle error
setUploading(false);
});
},
() => {
getDownloadURL(task.snapshot.ref).then((url) => {
setDownloadURL(url);
setUploading(false);
});
}
);
};

return (
Expand Down
8 changes: 4 additions & 4 deletions components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function Navbar() {
<nav className="navbar">
<ul>
<li>
<Link href="/">
<Link legacyBehavior href="/">
<button className="btn-logo">NXT</button>
</Link>
</li>
Expand All @@ -31,12 +31,12 @@ export default function Navbar() {
<button onClick={signOut}>Sign Out</button>
</li>
<li>
<Link href="/admin">
<Link legacyBehavior href="/admin">
<button className="btn-blue">Write Posts</button>
</Link>
</li>
<li>
<Link href={`/${username}`}>
<Link legacyBehavior href={`/${username}`}>
<img src={user?.photoURL || '/hacker.png'} />
</Link>
</li>
Expand All @@ -46,7 +46,7 @@ export default function Navbar() {
{/* user is not signed OR has not created username */}
{!username && (
<li>
<Link href="/enter">
<Link legacyBehavior href="/enter">
<button className="btn-blue">Log in</button>
</Link>
</li>
Expand Down
2 changes: 1 addition & 1 deletion components/PostContent.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default function PostContent({ post }) {
<h1>{post?.title}</h1>
<span className="text-sm">
Written by{' '}
<Link href={`/${post.username}/`}>
<Link legacyBehavior href={`/${post.username}/`}>
<a className="text-info">@{post.username}</a>
</Link>{' '}
on {createdAt.toISOString()}
Expand Down
6 changes: 3 additions & 3 deletions components/PostFeed.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ function PostItem({ post, admin = false }) {

return (
<div className="card">
<Link href={`/${post.username}`}>
<Link legacyBehavior href={`/${post.username}`}>
<a>
<strong>By @{post.username}</strong>
</a>
</Link>

<Link href={`/${post.username}/${post.slug}`}>
<Link legacyBehavior href={`/${post.username}/${post.slug}`}>
<h2>
<a>{post.title}</a>
</h2>
Expand All @@ -33,7 +33,7 @@ function PostItem({ post, admin = false }) {
{/* If admin view, show extra controls for user */}
{admin && (
<>
<Link href={`/admin/${post.slug}`}>
<Link legacyBehavior href={`/admin/${post.slug}`}>
<h3>
<button className="btn-blue">Edit</button>
</h3>
Expand Down
38 changes: 19 additions & 19 deletions lib/firebase.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getStorage } from 'firebase/storage';
import { GoogleAuthProvider } from 'firebase/auth';
import { getFirestore, collection, query, where, limit, getDocs } from "firebase/firestore";

const firebaseConfig = {
apiKey: 'AIzaSyBX5gkKsbOr1V0zxBuSqHWFct12dFOsQHA',
Expand All @@ -12,23 +13,18 @@ const firebaseConfig = {
appId: '1:827402452263:web:c9a4bea701665ddf15fd02',
};

if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
// TODO Check if app length check is still needed, firebase v10 docs don't seem to require it
const app = initializeApp(firebaseConfig);

// Auth exports
export const auth = firebase.auth();
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
export const auth = getAuth(app);
export const googleAuthProvider = new GoogleAuthProvider();

// Firestore exports
export const firestore = firebase.firestore();
export const serverTimestamp = firebase.firestore.FieldValue.serverTimestamp;
export const fromMillis = firebase.firestore.Timestamp.fromMillis;
export const increment = firebase.firestore.FieldValue.increment;
export const firestore = getFirestore(app);

// Storage exports
export const storage = firebase.storage();
export const STATE_CHANGED = firebase.storage.TaskEvent.STATE_CHANGED;
export const storage = getStorage(app);

/// Helper functions

Expand All @@ -37,10 +33,14 @@ export const STATE_CHANGED = firebase.storage.TaskEvent.STATE_CHANGED;
* @param {string} username
*/
export async function getUserWithUsername(username) {
const usersRef = firestore.collection('users');
const query = usersRef.where('username', '==', username).limit(1);
const userDoc = (await query.get()).docs[0];
return userDoc;
const usersRef = collection(firestore, 'users');
const userQuery = query(
usersRef,
where('username', '==', username),
limit(1)
);
const userDoc = await getDocs(userQuery);
return userDoc.docs[0];
}

/**`
Expand Down
6 changes: 3 additions & 3 deletions lib/hooks.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { auth, firestore } from '@lib/firebase';
import { doc, onSnapshot } from 'firebase/firestore';
import { useEffect, useState } from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';

// Custom hook to read auth record and user profile doc
export function useUserData() {
const [user] = useAuthState(auth);
const [user, loading, error] = useAuthState(auth);
const [username, setUsername] = useState(null);

useEffect(() => {
// turn off realtime subscription
let unsubscribe;

if (user) {
const ref = firestore.collection('users').doc(user.uid);
unsubscribe = ref.onSnapshot((doc) => {
unsubscribe = onSnapshot(doc(firestore, 'users', user.uid), (doc) => {
setUsername(doc.data()?.username);
});
} else {
Expand Down
Loading