Projects/JStargram

3일차 파이어베이스 로그인/로그아웃 및 채팅 구현

Nomad Kim 2021. 4. 9. 01:15

작업 내용

  • 파이어베이스를 이용하여 로그인 및 로그아웃을 구현
  • 사진에 대해 이야기를 나눌 수 있는 채팅 기능을 구현
  • 로그인 -> 채팅 기능 사용 가능
  • 로그인X-> 사진만 볼 수 있음
  • 상단으로 스크롤이동할 수 있는 버튼 추가
  • framer-motion 을 이용하여  애니메이션 적용.

App.js

1) 로그인/로그아웃

구글 로그인 및 로그아웃을 구현하기 위해 firebase 의 projectAuth(=firebase.auth()) 를 이용한다.

로그인 버튼을 누르면 google 창이 뜬다.

로그인/로그아웃 변화가 생길때마다 useEffect 에서 유저 로그인 상태를 저장한다.

import Title from "./comps/Title.js";
import UploadForm from "./comps/UploadForm";
import ImageGrid from "./comps/ImageGrid";
import styled from "styled-components";
import Modal from "./comps/Modal";
import { useState, useEffect } from "react";
import firebase from "firebase/app";
// import "firebase/firestore"; //database
import { projectAuth } from "./firebase/config";
import googlelogo from "./googlelogo.png";

function App() {
  const [selectedImg, setSelectedImg] = useState(null);
  const auth = projectAuth;
  const [user, setUser] = useState(() => auth.currentUser);
  const [initializing, setInitializing] = useState(true);

  const signInWithGoogle = async () => {
    //Retrieve Google provider object
    const provider = new firebase.auth.GoogleAuthProvider();
    //Set language to the default browser preference
    auth.useDeviceLanguage();
    //start signin process
    try {
      await auth.signInWithPopup(provider);
    } catch (error) {
      console.log(error);
    }
  };
  const signOut = async () => {
    try {
      await firebase.auth().signOut();
    } catch (error) {
      console.log(error.message);
    }
  };

  useEffect(() => {
    //this detects the change on state of user login
    const unsubscribe = auth.onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
      } else {
        setUser(null);
      }
      if (initializing) {
        setInitializing(false);
      }
    });
    //cleanup subscription(the state of login of user to logout)
    return unsubscribe;
  }, [initializing, auth]);
  //useEffect is on the process
  if (initializing) return "Loading...";

2) 스크롤

스크롤이 내려가면 top 버튼이 보여지고 버튼을 누르면 처음 화면으로 올라가도록 구현했다.

 // When the user scrolls down 20px from the top of the document, show the button
  window.onscroll = () => {
    scrollFunction();
  };

  function scrollFunction() {
    const topBtn = document.getElementById("topBtn");
    if (
      document.body.scrollTop > 20 ||
      document.documentElement.scrollTop > 20
    ) {
      topBtn.style.display = "block";
      topBtn.style.visibility = "visible";
      topBtn.style.opacity = 1;
      topBtn.style.transition = "all 2s";
    } else {
      topBtn.style.visibility = "hidden";
      topBtn.style.opacity = 0;
    }
  }

  // When the user clicks on the button, scroll to the top of the document
  function topFunction() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
  }

 

Overview

 

로그인X, 게스트일 경우, 사진을 볼 수 있다.

로그인 한 경우, 유저들과 사진에 대해 대화를 나눌 수 있다.

진행해야할 사항

  • 채팅 부분이 미흡하다. 메세지를 입력했을 때 자동으로 가장 최신의 메시지로 스크롤 이동해야 하는데, 아직 구현이 안됐다.
  • 로그인하지 않았을 경우, 그림을 업로드할 수 없도록 로직을 구현해야겠다.
  • 각 사진마다 다른 채팅방이 만들어져야 하므로 추가적인 변경이 필요하다.

오늘의 생각

  • 간단해 보이는 서비스도, 많은 정성이 필요하다.
  • Framer motion 라이브러리를 사용하여 사진이 추가되거나 클릭되었을 때 애니메이션 효과를 주었는데, 매우 편리하다.
  • 해당 서비스는 사진 감상과 사진에 대한 의견을 나누는 정도의 서비스이므로 추가적인 기능은 더 생각해봐야겠다.
  • 파이어베이스에서 데이터를 가져올 때, snapshot 즉 해당 저장공간을 캡쳐한다는 개념이 흥미롭다. 좀 더 익숙해지면 사용하기 쉬울 것 같다.