hmk run dev

파이어 베이스 복습 본문

React

파이어 베이스 복습

hmk run dev 2021. 3. 25. 10:33

firebase.js

import firebase from "firebase/app";
import "firebase/firestore";

const firebaseConfig = {
  apiKey: "AIzaSyC9rCMVUMT2SwB9TaE0Ww8ehtvD25oJ1J8",
  authDomain: "sparta-react-15fb3.firebaseapp.com",
  projectId: "sparta-react-15fb3",
  storageBucket: "sparta-react-15fb3.appspot.com",
  messagingSenderId: "971471391477",
  appId: "1:971471391477:web:29b4fc8ec136393b6d53bc",
  measurementId: "G-LEE70HB3B6",
};

firebase.initializeApp(firebaseConfig);

const firestore = firebase.firestore();

export { firestore };

 

 

App.js에서 파이어 스토어 연동 후 import { firestore } from "./firebase";

아래처럼 데이터를 가져 올 수 있다

  componentDidMount() {
    const bucket = firestore.collection("bucket"); // 여기서 파이어스토어 콜렉션에 접근

    bucket
      .doc("bucket_item1")
      .get()
      .then((doc) => {
        if (doc.exists) {
          console.log(doc.data());
          console.log(doc.id);
        }
        console.log(doc.exists);
      });

    bucket.get().then((docs) => {
      let bucket_data = [];
      docs.forEach((doc) => {
        if (doc.exists) {
          bucket_data = [...bucket_data, { id: doc.id, ...doc.data() }];
        }
      });
      console.log(bucket_data);
    });
  }

 

파이어베이스 데이터 관리

firebase.google.com/docs/firestore/manage-data/add-data?authuser=0

 

Cloud Firestore에 데이터 추가  |  Firebase

다음과 같은 몇 가지 방법으로 Cloud Firestore에 데이터를 쓸 수 있습니다. 문서 식별자를 명시적으로 지정하여 컬렉션 내의 문서 데이터를 설정합니다. 컬렉션에 새 문서를 추가합니다. 이 경우 Clo

firebase.google.com

추가하기

  bucket
      .add({ title: "캘리그라피 배우기", completed: false })
      .then((docRef) => {
        console.log(docRef);
        console.log(docRef.id);
      });

수정하기

bucket.doc("bucket_item1").update({ title: "코딩하기" });

삭제하기

  bucket
    .doc("bucket_item2")
     .delete()
     .then((docRef) => {
       console.log("지웠어요!");
      });

안에 정보가 있나없나 확인하는 방법

const todo = firestore.collection("todo");

todo
  .doc("todo_item2") // 아이템2 라는 저장소 자체가 없다
  .get()
  .then((doc) => {
    if (doc.exists) {
      console.log(doc);
      console.log(doc.data());
      console.log(doc.id);
    }
    console.log(doc.exists);
  }); >> 없으니 false 출력

데이터 어레이로 뽑아오기

 

 

 

Comments