From a1420da0e7659ec80afc2a1fb92e88879d831d77 Mon Sep 17 00:00:00 2001 From: angelp03 Date: Thu, 7 Nov 2024 21:42:28 -0600 Subject: [PATCH] add findCafePosts function --- src/utilities/firebase.js | 5 ++++- src/utilities/posts.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 src/utilities/posts.js diff --git a/src/utilities/firebase.js b/src/utilities/firebase.js index 10332d1..21aff47 100644 --- a/src/utilities/firebase.js +++ b/src/utilities/firebase.js @@ -21,6 +21,7 @@ const firebaseConfig = { const app = initializeApp(firebaseConfig); const auth = getAuth(app); const provider = new GoogleAuthProvider(); +const database = getDatabase(app); export const signInWithGoogle = () => { @@ -76,4 +77,6 @@ export const useDbUpdate = (path) => { ); return [updateData, result]; -}; \ No newline at end of file +}; + +export {database}; \ No newline at end of file diff --git a/src/utilities/posts.js b/src/utilities/posts.js new file mode 100644 index 0000000..d1f47f1 --- /dev/null +++ b/src/utilities/posts.js @@ -0,0 +1,33 @@ +import { useState, useEffect } from 'react'; +import { onValue, query, orderByChild, equalTo, ref } from 'firebase/database'; +import { database } from './firebase'; + +export const findCafePosts = (cafeId) => { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + if (!cafeId) return + + const postsRef = ref(database, `/posts`); + const postsQuery = query(postsRef, orderByChild('cafeId'), equalTo(cafeId)); + + const unsubscribe = onValue( + postsQuery, + (snapshot) => { + if (snapshot.exists()) { + setData(snapshot.val()); + } else { + setData([]); + } + }, + (error) => { + setError(error); + } + ); + + return () => unsubscribe(); + }, [cafeId]); + + return [data, error]; +}; \ No newline at end of file