Skip to content

add user={undefined} to UserProfile.js #19

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

Open
wants to merge 6 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
12 changes: 7 additions & 5 deletions components/HeartButton.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { firestore, auth, increment } from '@lib/firebase';
import { firestore, auth } from '@lib/firebase';
import { useDocument } from 'react-firebase-hooks/firestore';
import { increment, writeBatch, doc, getFirestore } from "firebase/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(getFirestore(), postRef.path, '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(getFirestore());

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

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

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
7 changes: 4 additions & 3 deletions components/ImageUploader.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { auth, storage, STATE_CHANGED } from '@lib/firebase';
import Loader from './Loader';
import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage';

// Uploads images to Firebase Storage
export default function ImageUploader() {
Expand All @@ -15,11 +16,11 @@ 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);
const task = uploadBytesResumable(fileRef, file)

// Listen to updates to upload task
task.on(STATE_CHANGED, (snapshot) => {
Expand All @@ -29,7 +30,7 @@ export default function ImageUploader() {

// Get downloadURL AFTER task resolves (Note: this is not a native Promise)
task
.then((d) => ref.getDownloadURL())
.then((d) => getDownloadURL(fileRef))
.then((url) => {
setDownloadURL(url);
setUploading(false);
Expand Down
7 changes: 4 additions & 3 deletions components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ import { useRouter } from 'next/router';
import { useContext } from 'react';
import { UserContext } from '@lib/context';
import { auth } from '@lib/firebase';
import { signOut } from 'firebase/auth';

// Top navbar
export default function Navbar() {
const { user, username } = useContext(UserContext);

const router = useRouter();

const signOut = () => {
auth.signOut();
const signOutNow = () => {
signOut(auth);
router.reload();
}

Expand All @@ -28,7 +29,7 @@ export default function Navbar() {
{username && (
<>
<li className="push-left">
<button onClick={signOut}>Sign Out</button>
<button onClick={signOutNow}>Sign Out</button>
</li>
<li>
<Link href="/admin">
Expand Down
69 changes: 52 additions & 17 deletions lib/firebase.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';
// import firebase from 'firebase/compat/app'
// import 'firebase/compat/auth';
// import 'firebase/compat/firestore';
// import 'firebase/compat/storage';

import { initializeApp, getApps, getApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";
import { getFirestore, collection, where, getDocs, query, limit } from "firebase/firestore";
import { getStorage } from "firebase/storage";



const firebaseConfig = {
apiKey: 'AIzaSyBX5gkKsbOr1V0zxBuSqHWFct12dFOsQHA',
Expand All @@ -12,34 +19,62 @@ const firebaseConfig = {
appId: '1:827402452263:web:c9a4bea701665ddf15fd02',
};

if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
// Initialize firebase
// let firebaseApp;
// let firestore;
// if (!getApps().length) {
// // firebase.initializeApp(firebaseConfig);
// initializeApp(firebaseConfig);
// firestore = getFirestore();
// }

function createFirebaseApp(config) {
try {
return getApp();
} catch {
return initializeApp(config);
}
}

// const firebaseApp = initializeApp(firebaseConfig);
const firebaseApp = createFirebaseApp(firebaseConfig);



// Auth exports
export const auth = firebase.auth();
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
// export const auth = firebase.auth();
export const auth = getAuth(firebaseApp);
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(firebaseApp);
// export const firestore = firebase.firestore();
// export { firestore };
// export const serverTimestamp = serverTimestamp;
// export const fromMillis = fromMillis;
// export const increment = increment;

// Storage exports
export const storage = firebase.storage();
export const STATE_CHANGED = firebase.storage.TaskEvent.STATE_CHANGED;
export const storage = getStorage(firebaseApp);
export const STATE_CHANGED = 'state_changed';

/// Helper functions


/**`
* Gets a users/{uid} document with username
* @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];
// const usersRef = collection(firestore, 'users');
// const query = usersRef.where('username', '==', username).limit(1);

const q = query(
collection(firestore, 'users'),
where('username', '==', username),
limit(1)
)
const userDoc = ( await getDocs(q) ).docs[0];
return userDoc;
}

Expand Down
6 changes: 4 additions & 2 deletions lib/hooks.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { doc, onSnapshot, getFirestore } from 'firebase/firestore';
import { auth, firestore } from '@lib/firebase';
import { useEffect, useState } from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';
Expand All @@ -12,8 +13,9 @@ export function useUserData() {
let unsubscribe;

if (user) {
const ref = firestore.collection('users').doc(user.uid);
unsubscribe = ref.onSnapshot((doc) => {
// const ref = firestore.collection('users').doc(user.uid);
const ref = doc(getFirestore(), 'users', user.uid);
unsubscribe = onSnapshot(ref, (doc) => {
setUsername(doc.data()?.username);
});
} else {
Expand Down
5 changes: 4 additions & 1 deletion next.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
module.exports = {
swcMinify: true,
}
experimental: {
esmExternals: false
}
}
Loading