[Firebase]기본 문법 정리

코드왕·2022년 8월 11일
0

FIREBASE v9의 모든 것!

1. firebase 기본파일 생성

import { initializeApp } from "firebase/app";
import {getAuth} from 'firebase/auth'
import 'firebase/database'
import {getFirestore} from 'firebase/firestore'
import {getStorage} from 'firebase/storage'

//로그인 정보 기재란↓↓↓↓

const firebaseConfig = { 
  apiKey: "AIzaSyAWelhigl-LTubC0235SIQOpv6Amz4iZT0",
  authDomain: "carrot-52f64.firebaseapp.com",
  projectId: "carrot-52f64",
  storageBucket: "carrot-52f64.appspot.com",
  messagingSenderId: "677389289098",
  appId: "1:677389289098:web:8dfd4c5280875dd68acf73"
};

//앱 스타트 및 Auth,DB,Storage 스타트↓↓↓↓

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const authService = getAuth();
export const dbService = getFirestore();
export const storageService=getStorage();

▶ firebase.js 파일을 만들고 위의 내용을 붙여 넣어준다.
▶ firebase 홈페이지에서 로그인 정보를 가져오고, Auth,DB,Storage를 시작할 수 있도록 export 해준다.

2. 필요한 시스템 Import

import {authService} from '../firebase' //Auth쓸때
import {dbService} from '../firebase' //DB쓸때
import { storageService } from '../firebase'//Storage쓸때

▶필요한 기능을 쓸 때 위의 component를 Import 해준다.

3. 주요 기능 Import

import {addDoc,collection, doc, getDocs,query,onSnapshot,orderBy, setDoc} from 'firebase/firestore' // firestore DB에 주로 쓰는 기능들
import { getDownloadURL,uploadString,uploadBytes} from 'firebase/storage'//storage에 주로 쓰는 기능들
import {getAuth,signInWithEmailAndPassword,createUserWithEmailAndPassword,signInWithPopup,GoogleAuthProvider,GithubAuthProvider,updateProfile,signOut,onAuthStateChanged} from 'firebase/auth' //Auth에 주로 쓰는 기능들

4. 기능별 사용법

▶ 각 시스템 마다 주로 사용하는 기능들이 있다. Import하고 문법에 맡게 사용해보자.

/////Auth 관련
await createUserWithEmailAndPassword(authService,email,password) //회원가입하기
await signInWithEmailAndPassword(authService,email,password) //로그인하기
await signOut(authService) //로그아웃하기
await onAuthStateChanged(authService,(user)=>{cb}) // 로그인 한 정보 확인하기

▶ 주요 명령어를 사용하여 가입과 로그인,로그아웃을 구현한다.

////firestore db들 가져오기
const getProducts=async ()=>{  
  const q=query(collection(dbService,"product"))
  const querySnapshot=await getDocs(q)
  querySnapshot.forEach((doc)=>{
    const newOne=doc.data()
    setProducts((prev)=>{
      if (prev.length<querySnapshot.size){
        return [newOne,...prev]
      } else {
        return prev
      }
    })
  })
}

const docRef=await addDoc(collection(dbService,'product'),{ //DB내용 추가
      제목:title,
      게시일:dateString,
      가격:price,
      content:content,
      URL:imageUrl,
      uid:uid,
    })

const docRef=await addDoc(collection(dbService,'chatroom',roomName,'messages'),{
      content:"111",
    })    //db안의 db에 내용 추가

▶ query 명령어를 사용하여 firestore에 있는 정보들을 가져온다.

// 그림 파일 저장 방법(Blob)
  const handleImage= (event)=>{
    const {target:{files}}=event;
    const theFile=files[0];
    setFile(theFile)
    const reader = new FileReader();
    reader.onloadend=(finishedEvent)=>{
      const {currentTarget:{result}}=finishedEvent
      setImage(result)
    }
    reader.readAsDataURL(theFile)
  }
  
  const handleClick= async ()=>{
    let today=new Date();
    var year = today.getFullYear();
    var month = ('0' + (today.getMonth() + 1)).slice(-2);
    var day = ('0' + today.getDate()).slice(-2);
    var dateString = year + '년' + month  + '월' + day + '일';

//Blob파일 storageService에 저장하고 downloadUrl추출하기
    let imageUrl=""
    if (image!==""){
      const imageRef = ref(storageService, `image/${file.name}`);
      const response = await uploadString(imageRef, image, "data_url");
      imageUrl = await getDownloadURL(response.ref);
    } else{
      imageUrl=""
    }  
profile
CODE DIVE!

0개의 댓글