FireBase 사용하기

JH L·2022년 9월 18일
0

1. react 프로젝트 생성

npx create-react-app my-app
npm install firebase

2. firebase 프로젝트 생성





3. firebase-config.js 생성

import { initializeApp } from "firebase/app";
import { getFirestore } from '@firebase/firestore'

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

const app = initializeApp(firebaseConfig);

export const db = getFirestore(app);

4. firebase database 생성




asia-northeast3 (서울)



false → true



5. firebase CRUD

CREATE

import { db } from './firebase-config';
import { collection, addDoc } from 'firebase/firestore';

function App () {
  const usersCollectionRef = collection(db, 'users');
  
  const createUser = async () => {
    await addDoc(usersCollectionRef, {
      name: 'park', age: 15
    });
  }
  
  return (
    <div>
      <button onClick={() => createUser()}></button>
    </div>
  )
}

export default App;

READ

import { db } from './firebase-config';
import { collection, getDocs } from 'firebase/firestore';

const [users, setUsers] = useState([]);
const usersCollectionRef = collection(db, 'users');
const getUsers = async () => {
  const data = await getDocs(usersCollectionRef);
  setUsers(data.docs.map((doc) => {
    return {...doc.data(), id: doc.id};
  }));
}

UPDATE

import { db } from './firebase-config';
import { doc, updateDoc } from 'firebase/firestore';

const updateUser = async (id, age) => {
  const userDoc = doc(db, "users", id);
  const newFields = { age: age + 1 };
  await updateDoc(userDoc, newFields);
}

DELETE

import { db } from './firebase-config';
import { doc, deleteDoc } from 'firebase/firestore';

const deleteUser = async (id) => {
  const userDoc = doc(db, "users", id);
  deleteDoc(userDoc);
}
profile
...

0개의 댓글