Firebase 등록, 불러오기 feat. 날짜 순

준영·2023년 2월 23일
0

Firebase를 써보자..

목록 보기
3/8
post-thumbnail

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,
};

// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const firebaseAuth = getAuth(firebaseApp);
const firebaseDb = getFirestore(firebaseApp);

export {
  firebaseAuth,
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  firebaseDb,
  firebaseApp,
};

import

// firebase
import {
  addDoc,
  collection,
  getFirestore,
  getDocs,
  query,
  orderBy,
} from "firebase/firestore";
import { firebaseApp, firebaseDb } from "../../../firebase.config";

create data func

// create comment func
const submitComment = async () => {
  if (loginStatus == true && userInfo.email != "") {
    // visitlog라는 컬렉션이 없으면 생성해서 다음의 필드에 데이터를 넣음
    await addDoc(collection(firebaseDb, "visitlog"), {
      name: name,
      comment: comment,
      timestamp: new Date(),
    });
    // 데이터를 입력하고, fetch 함수로 데이터를 불러오기
    fetchComments();
    // input 초기화
    setComment("");
    // comments list 영역 스크롤 최상단으로 이동
    listRef.current.scrollTop = 0;
  } else {
    router.push("/login");
  }
};
  • fetch 할 때, 등록 순으로 정렬해서 불러오기 위해 timestamp: new Date() 객체를 불러왔음

  • addDoc은 setDoc과 다르게 id값을 무작위로 생성한다.

fetch data func

// fetch comments 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);
}

// first time fetch (최초 데이터 불러오기)
useEffect(() => {
  fetchComments();
}, []);
  • 아까 등록 할 때 넣어준 timestamp라는 필드값을 기준으로 정렬해준다
profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글