Firebase
Firebase + React Setup
๋ฆฌ์กํธ ํ๋ก์ ํธ ์์ฑ
Firebase ํ๋ก์ ํธ ์์ฑ
npm install firebase
firebase.js ์์ฑ
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
};
const app = initializeApp(firebaseConfig);
export default app;
index.js import
import firebase from "firebase/compat/app";
.env ์์ฑ (firebase key๋ค์ ํ๊ฒฝ๋ณ์๋ก ์ค์ , Github์ ์ฌ๋ผ๊ฐ์ง ์๊ฒ)
// .env
REACT_APP_API_KEY = ...
// src/firebase.js
apiKey: process.env.REACT_APP_API_KEY,
Authentication
// fbase.js
import { getAuth } from "firebase/auth";
...
export const authService = getAuth();
createUserWithEmailAndPassword(authService, email, password) : ๋ฉ์ผ๊ณผ ํจ์ค์๋๋ก ์ธ์ฆํ๋ ์ฌ์ฉ์ ๊ณ์ ์ ๋ง๋ฌ
signInWithPopup(aushService, provider) : ์ธ์ฆ ์ ๊ณต์๊ฐ ์ ๊ณตํ๋ ์ ๋ณด๋ฅผ ํตํด ์ธ์ฆ
signOut(authService) : ํ์ฌ ์ฌ์ฉ์๋ฅผ ๋ก๊ทธ์์
Firestore
NoSQL Database๋ก ์ ์ฐํจ, ์ ํ์ฌํญ์ด ์์(์์ ๋ ๋ฎ์)
Database > Collection : ํด๋ > Document : ๋ฌธ์
// doc ์์ฑ
const onSubmit = async (event) => {
event.preventDefault();
await addDoc(collection(dbService, "tweets"), {
tweet,
createAt: Date.now(),
});
setTweet("");
};
// doc ๊ฐ์ ธ์ค๊ธฐ
const getTweets = async () => {
const dbTweets = await getDocs(collection(dbService, "tweets"));
dbTweets.forEach((document) => {
const tweetObj = {
...document.data(),
id: document.id,
};
setTweets((prev) => [tweetObj, ...prev]);
});
};
or
// onSnapshot์ ์ด์ฉํ๋ฉด db์ ๋ณ๋์ฌํญ์ด ์๊ธธ๋๋ง๋ค ๊ฐฑ์ (listener)
useEffect(() => {
onSnapshot(collection(dbService, "tweets"), (snapshot) => {
const tweetArray = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
setTweets(tweetArray);
});
}, []);
// doc ์ญ์
await deleteDoc(doc(dbService, "tweets", `${tweetObj.id}`));
// doc ์
๋ฐ์ดํธ
await updateDoc(doc(dbService, "tweets", `${tweetObj.id}`), {
text: newTweet,
});
Last updated