Firebase

Firebase + React Setup

  1. ๋ฆฌ์•กํŠธ ํ”„๋กœ์ ํŠธ ์ƒ์„ฑ

  2. Firebase ํ”„๋กœ์ ํŠธ ์ƒ์„ฑ

  3. npm install firebase

  4. firebase.js ์ƒ์„ฑ

import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
};

const app = initializeApp(firebaseConfig);

export default app;
  1. index.js import

import firebase from "firebase/compat/app";
  1. .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