김 양의 멋따라 개발따기
22.12.20./Firebase firestore 이용하기 본문
1. Firebase란?
- 웹의 동작방식
- 웹은 서버와 클라이언트 사이의 요청과 응답으로 동작
- 클라이언트가 서버에게 요청하면 서버가 클라이언트에게 응답하는 방식
- 서버리스
- 서버가 없는 것이 아닌 서버를 신경쓸 필요가 없는 것
- 이미 구축해둔 서버의 일부분을 빌려서 사용 가능
- BaaS 란?
- Backend as a Service의 약자
- firebase는 데이터 베이스, 소셜 서비스 연동, 파일 시스템 등을 API 형태로 제공
2. Firebase 시작하기
//1. firebase 설치
npm install firebase
//or
yarn add firebase
//firebase.js 설정
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
***자동 완성하면 import 경로가 "firebase/firestore/lite"로 되는데 꼭 lite를 삭제해주어야 함!!!
3. 데이터 CRUD
- 데이터 읽기
import { db } from "./firebase";
import { collection, getDocs } from "firebase/firestore";
...
function async fetchData() {
const data = await getDocs(collection(db, "bucket"));
data.forEach((doc) => {
console.log(doc.id, doc.data());
});
}
fetchData();
//getDocs로 모든 데이터를 가지고 와
//forEach로 각각의 데이터를 가지고 올 수 있음
- 데이터 쓰기
import { db } from "./firebase";
import { collection, addDoc } from "firebase/firestore";
...
function fetchData async () {
const docRef = await addDoc(collection(db, "콜랙션명"), {
name : "Rive"
});
}
fetchData();
//addDoc을 이용해 data를 넣어줌
- 데이터 수정하기
import { db } from "./firebase";
import { collection, doc, updateDoc } from "firebase/firestore";
...
async function fetchData() {
const docRef = doc(db, "콜랙션명", "문서명");
await updateDoc(docRef, {
name:"sieo",
});
}
fetchData();
//updateDoc을 이용해서 업데이트 가능
- 데이터 삭제하기
import { db } from "./firebase";
import { collection, doc, deleteDoc } from "firebase/firestore";
...
function fetchData async() {
const docRef = doc(db, "콜랙션명", "문서명");
await deleteDoc(docRef);
}
fetchData();
//deleteDoc을 이용해 삭제 가능
****자동 완성하면 import 경로가 "firebase/firestore/lite"로 되는데 꼭 lite를 삭제해주어야 함!!!
'TIL' 카테고리의 다른 글
22.12.28./(React-Typescript)form에서 event.preventDefault()의 event type (0) | 2022.12.28 |
---|---|
22.12.24./firebase realtime database를 이용한 실시간 채팅 구현기 (2) | 2022.12.24 |
2022.08.08. TIL(브라우저) (0) | 2022.12.14 |
22.12.09./CLS(Cumulative Layout Shift)와 개선 방법 (0) | 2022.12.10 |
22.12.09. FID(First Input Delay)와 개선법 (1) | 2022.12.09 |