티스토리 뷰

프론트엔드/React

FireStore 데이터

yyoujg 2022. 6. 8. 00:29

1)app.js에서 firestore 데이터 사용하기

(1) 데이터 전체 읽어오기

collection()으로 찾은 다음, getDocs()로 콜렉션 내의 데이터를 가져온다.

그리고 forEach문으로 내용을 확인할 수 있다. (배열이 아니기 때문)

import { db } from "./firebase";
import { collection, getDoc, getDocs } from "firebase/firestore";
...
React.useEffect(async() => {
    const query = await getDocs(collection(db, 'bucket'));
		console.log(query);
    query.forEach((doc) => {
      console.log(doc.id, doc.data());
    });
  }, []);

(2) 데이터 추가하기

콜렉션을 찾고 addDoc() → 대시보드에서 찰 추가되었는지 확인

import { db } from "./firebase";
import { collection, addDoc } from "firebase/firestore";
...
const docRef = await addDoc(collection(db, 'bucket'), {
     completed: false,
     text: "new"
   })

(3) 데이터 수정하기

콜렉션을 찾고 도큐먼트 id로 updateDoc()

import { db } from "./firebase";
import { collection, doc, updateDoc } from "firebase/firestore";
...
React.useEffect(async() => {
    const docRef = doc(db, "bucket", "P5Oz4GbccEg9uaca8sJG");
    await updateDoc(docRef, {
      completed: true,
    });

  }, []);

(4) 데이터 삭제하기

콜렉션을 찾고 도큐먼트 id로 updateDoc()

import { db } from "./firebase";
import { collection, doc, deleteDoc } from "firebase/firestore";
...
React.useEffect(async() => {
    const docRef = doc(db, "bucket", "P5Oz4GbccEg9uaca8sJG");
    await deleteDoc(docRef);

  }, []);

2) 콜렉션 이름 변경하기

(1) 콜렉션 이름을 바꿔서 추가하기

// bucket에서 buckets로 이름 바꾸기! 그리고 대시보드를 확인
import { db } from "./firebase";
import { collection, addDoc } from "firebase/firestore";
...
const docRef = await addDoc(collection(db, 'buckets'), {
     completed: false,
     text: "new"
   })

 

'프론트엔드 > React' 카테고리의 다른 글

React Hooks - useEffect  (0) 2022.06.08
React Hooks - useState  (0) 2022.06.08
리액트에 Firebase 연동하기  (0) 2022.06.08
Firebase  (0) 2022.06.08
회원가입 구현하기 (feat. firestore)  (0) 2022.06.07
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함