firebase.config
import { initializeApp } from "firebase/app";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
} from "firebase/auth";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
};
const firebaseApp = initializeApp(firebaseConfig);
const firebaseAuth = getAuth(firebaseApp);
const firebaseDb = getFirestore(firebaseApp);
export {
firebaseAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
firebaseDb,
firebaseApp,
};
import
import {
addDoc,
collection,
getFirestore,
getDocs,
query,
orderBy,
} from "firebase/firestore";
import { firebaseApp, firebaseDb } from "../../../firebase.config";
create data func
const submitComment = async () => {
if (loginStatus == true && userInfo.email != "") {
await addDoc(collection(firebaseDb, "visitlog"), {
name: name,
comment: comment,
timestamp: new Date(),
});
fetchComments();
setComment("");
listRef.current.scrollTop = 0;
} else {
router.push("/login");
}
};
- fetch 할 때, 등록 순으로 정렬해서 불러오기 위해
timestamp: new Date()
객체를 불러왔음
- addDoc은 setDoc과 다르게 id값을 무작위로 생성한다.
fetch data func
async function fetchComments() {
const visitlog = collection(getFirestore(firebaseApp), "visitlog");
const result = await getDocs(query(visitlog, orderBy("timestamp", "desc")));
const fetchData = result.docs.map((el) => el.data());
setCommentsData(fetchData);
}
useEffect(() => {
fetchComments();
}, []);
- 아까 등록 할 때 넣어준 timestamp라는 필드값을 기준으로 정렬해준다