오늘은 다른분들의 도움을 받아서 파이어베이스에서 crud를 위한 값을 불러오는 법을 배웠다.
생각해보니 여태껏 파이어베이스에서 값을 가져올만한 프로젝트들을 해보지 않고 있는 값들을 정리하는 프로젝트들을 하다보니...
그렇게 되었다ㅎㅎ...ㅜㅜ

여하튼 예시로써 코드를 전달해주셔서 그나마 수월하게 진행했던 것같다.

// 파이어베이스 snapshot을 사용하여 데이터 가져오기 
import styled from "@emotion/styled";
import { collection, getDocs, onSnapshot, query } from "firebase/firestore";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { db } from "../../common/firebase";
import CardSection from "../../shared/CardSection";
const Search = () => {
    const params = useParams();
    const [searchData, setSearchData] = useState([]);

// useEffect를 감싸지 않고 따로 작성도 가능한 버전이 있다. 차후에 작성될 예정.
    useEffect(() => {
        const postCollectionRef = collection(db, 'post');
        const q = query(postCollectionRef);
        const getPost = onSnapshot(q, (snapshot) => {
            const testPost = snapshot.docs.map((doc) => ({
                id: doc.id,
                ...doc.data(),
            }));
            setSearchData(testPost)
        })
        return getPost;
    }, [])

아참 여기서 snapshot을 사용하는 이유는 값이 변화하면 다시 새로고침을 하게 되는데, 여기서 snapshot은 새로고침을 하지 않고 변하는 값만 쏙! 빼온다고 들었다.
(틀렸으면 수정하겠음!)

왜 이 코드가 사용되는지는 알고 쓰고싶었기도 했고, 어차피 실무에선 파이어베이스를 잘 사용하지 않으니까~ 하고 대충 공부하고 좀 피해다녔는데 후회가 조금 되는 순간이었다....ㅎㅅㅎ..ㅜㅜㅜㅜㅜㅜㅜ

profile
프론트엔드 개발 과정을 기록 중입니다:)

0개의 댓글