본문 바로가기

공부/React

React에서 firebase 사용하기

01. firebase 가입 후 firebaseConfig 얻기

firebase에 가입하고 새 프로젝트를 만들고 설정에 들어가면 "Your web app's Firebase configuration" 이라는 웹 앱의 Firebase 구성 소스가 제공된다.

내 프로젝트에서 api라는 폴더를 만들고 그 안의 firebase.js 파일에 해당 구성 소스를 복사했다.

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

02. 가이드라인에 따라 로그인, 로그아웃 팝업 기능이 담긴 소스 넣기 

firebase 공식문서에 따라 optional 코드를 제외하고 완성된 코드는 아래와 같다.

import { initializeApp } from "firebase/app";
import {
    getAuth,
    signInWithPopup,
    signOut,
    GoogleAuthProvider,
} from "firebase/auth";

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
};

const app = initializeApp(firebaseConfig);
const auth = getAuth();
const provider = new GoogleAuthProvider();

signInWithPopup(auth, provider)
    .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // ...
    })
    .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
    });

signOut(auth)
    .then(() => {
        // Sign-out successful.
    })
    .catch((error) => {
        // An error happened.
    });

03. 함수 만들어 사용하기 

firebase.js 안에있는 signInWithPopup, signOut 를 함수화 해서 export한다.

이러면 다른곳에서 사용할 때, 성공하든 실패하든 그 결과를 promise로 받아 우리가 원하는 result.user 값을 state로 받아 사용하면 된다.

04. 로그인 상태라면 캐싱하기 

Set an authentication state observer and get user data

여태까지 작성한 코드로 로그인/로그아웃은 잘 되지만, 새로고침 하는 순간 다시 로그아웃이 되버리는 문제가 있다. 

이를 해결하기 위해 useEffect와 firebase에서 제공하는 onAuthStateChanged 함수를 사용하면 된다.

 

우선, 만들어둔 firebase.js에 아래의 내용이 담긴 새로운 함수를 추가한다.

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

 

새로운 함수에는 로그인 상태가 변경될때마다 실행될 callback 함수를 불러오도록 하면 된다.

firebase.js에 함수를 export 해두었으니 필요한 곳에서 호출하면 되고,

호출하는 곳에서 callback함수를 정의해서 user state (로그인 상태)를 관리하면 될 것 같다. 

잘 작동된다면 사용자가 아무리 새로고침해도 useEffect가 로그인 상태를 파악할 것이고,

만약에 상태가 달라졌을 경우에만 callback함수가 실행되어 user 상태가 변경될 것이다.

 

 

* 함수 만들어 사용하는 과정은 생략함

'공부 > React' 카테고리의 다른 글

React Context 사용하기  (0) 2023.02.03
React 에서 .env 파일이란?  (0) 2023.02.01
React에서 Tailwindcss 시작하기  (0) 2023.02.01
노마드코더 강의 : React 시작하기 (고전 방법)  (0) 2023.01.27