Firebase 사용법
사용법
설치 및 세팅
- 프로젝트 생성
- firebase에 프로젝트 생성
- 앱 추가
- local에 firebase 추가
npm install --save firebase
- firebase 구성 객체 입력
import * as firebase from "firebase/app";
const firebaseConfig = {
apiKey: "api-key",
authDomain: "project-id.firebaseapp.com",
databaseURL: "https://project-id.firebaseio.com",
projectId: "project-id",
storageBucket: "project-id.appspot.com",
messagingSenderId: "sender-id",
appID: "app-id",
};
firebase.initializeApp(firebaseConfig);
export const firebaseInstance = firebase;
+ create-react-app으로 만들어 환경변수를 사용하려면 REACT_APP_'환경변수'
+ git ignore에 .env를 추가해서 github에 추가되는것을 막는다. 빌드하면 결국은 변환되어 값이 나타나므로 보안사항은 아니고
Cloud Firestore
- 새로운 데이터 베이스 만들기
- 테스트 모드에서 시작
- 지역 설정(Asia.NorthEast)
- 사용 설치
- fbase에 firestore/firestore import하기
- Collect
- collect은 document의 그룹이다.
- Data 추가
const onSubmit = async (event) => {
event.preventDefault();
await dbService.collection("nweets").add({
nweet: nweet,
createdAt: Date.now(),
});
setNweet("");
};
-nweets라는 collection에 document가 저장 5. Data 불러오기
const getNweets = async () => {
const dbNweets = await dbService.collection("nweets").get();
dbNweets.forEach((document) => {
const nweetObject = {
...document.data(),
id: document.id,
};
setNweets((prev) => [nweetObject, ...prev]);
});
};
useEffect(() => {
getNweets();
}, []);
- get하면 QuerySnapshot이라는것을 불러온다.
- 그중에 data를 가져옴.
- 실시간
useEffect(() => {
// getNweets();
//실시간 업데이트 반영
dbService.collection("nweets").onSnapshot((snapshot) => {
const nweetArray = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
setNweets(nweetArray);
});
}, []);
- listener로 snapshot을 사용
- onSnapshot : database의 변화를 실시간으로 알려준다.
- 앞의 forEach 사용 없이 실시간으로 구성 가능
- deploy
npm i gh-pages
- gh-pages 설치
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
...
"homepage": " https://2nd-deck.github.io/nwitter"
- package.json에 추가
npm run deploy
- deploy 실행
- security
- firebase-Authentication- Sign-in method - 승인된 도메인- 현재 사용중인 도메인 추가
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
- firestore-규칙- 로그인한 사람만 수정가능하게 변경
- https://console.developers.google.com/apis/credentials에 접속
- project 선택
- browser key
- 애플리케이션 제한사항에 HTTP 리퍼러 선택
- 웹사이트 제한사항- 항목추가- 사용중인 웹사이트와 localhost 그리고 firebase 도메인 추가
- firebase 도메인은 Authentication- Sign-in method - 승인된 도메인에 있음
- 추가한 도메인에서의 요청만 수락
- web client key도 동일하게
- firebase Function을 이용해서 NoSQL 데이터 베이스에서 할수 없는 부분을 할 수 있다.