20240206 TIL#32
[1] TIL
1. Firebase 특강 정리 - firebase 사용법
(1) Firebase 환경 설정
1) Firebase 사이트에서 프로젝트 추가
2) VS code에서 npm install firebase
3) src 폴더에 firebase.js 파일 만들고 초기 설정
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: ---
authDomain: "react-news-feed-71a36.firebaseapp.com",
projectId: "react-news-feed-71a36",
storageBucket: "react-news-feed-71a36.appspot.com",
messagingSenderId: "287134483382",
appId: ---
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
4) index.js에서 firebase.js import하고 data 잘 들어오는 지 확인
5) root에 .env 파일 만들어서 API key를 환경 변수로 설정하기
REACT_APP_API_KEY = ------
REACT_APP_AUTH_DOMAIN = react-practice-02.firebaseapp.com
REACT_APP_PROJECT_ID = react-practice-02
REACT_APP_STORAGE_BUCKET = react-practice-02.appspot.com
REACT_APP_MESSAGING_SENDER_ID = 211680733037
REACT_APP_APP_ID = -------
(2) Authentication 이용
1) 로그인, 회원가입, 소셜 로그인, 유저 관리 등의 사용자 인증을 구축하는 서비스
2) firebase.js에 auth 관련 코드 추가
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
3) Firebase 콘솔에서 로그인 방법 설정하기
4) createUserWithEmailAndPassword, siginInWithEmailAndPassword 함수를 이용하여 회원가입, 이메일과 비밀번호로
로그인할 수 있도록 설정하기
(3) FireStore로 데이터 다루기
1) Firestore의 데이터
Document : 객체 형태로 저장되는 document로 구성되며 고유한 id를 가짐.
Collection : document는 collection에 저장됨.
2) firesbase 콘솔에서 보얀 규칙을 적용하고 위치를 설정한 뒤 데이터베이스를 만들기
3) firebase에 관련 코드 추가
import { initializeApp } from "firebase/app";
...
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
...
export const db = getFirestore(app);
4) query 조건문으로 데이터를 가져오기
- collection( ) : 특정 컬렉션 선택
- where( ) : 지정된 필드에 대한 조건 지정
- getDocs로 qeury를 가져온 뒤 querySnapshot method로 가져온 문서들에 대한 정보와 문서에 접근
- 데이터 추가는 addDoc, 수정은 updateDoc, 삭제는 deleteDoc
// components/Todo.js
import { collection, getDocs, query } from "firebase/firestore";
import { db } from "../firebase";
...
useEffect(() => {
const fetchData = async () => {
const q = query(collection(db, "todos"));
const querySnapshot = await getDocs(q);
...
}, []);
(4) Storage
1) firebase 콘솔에서 storage 시작하기
2) firebase.js에 코드 추가하기
import { initializeApp } from "firebase/app";
...
import { getStorage } from "firebase/storage";
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
...
export const storage = getStorage(app);