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

2021. 4. 9. 01:15·Projects/JStargram_2021

작업 내용

  • 파이어베이스를 이용하여 로그인 및 로그아웃을 구현
  • 사진에 대해 이야기를 나눌 수 있는 채팅 기능을 구현
  • 로그인 -> 채팅 기능 사용 가능
  • 로그인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 즉 해당 저장공간을 캡쳐한다는 개념이 흥미롭다. 좀 더 익숙해지면 사용하기 쉬울 것 같다.

'Projects > JStargram_2021' 카테고리의 다른 글

4일차 CSS/기능 리팩토링 및 배포 완료  (0) 2021.04.09
2일차 사진 갤러리 로직 및 CSS 완료  (0) 2021.04.08
1일차 셋업/기본 로직 구현  (0) 2021.04.08
'Projects/JStargram_2021' 카테고리의 다른 글
  • 4일차 CSS/기능 리팩토링 및 배포 완료
  • 2일차 사진 갤러리 로직 및 CSS 완료
  • 1일차 셋업/기본 로직 구현
JTB
JTB
웹/앱 개발 정보를 공유하고 있습니다.
  • JTB
    JTechBlog
    JTB
  • 전체
    오늘
    어제
    • All About Programming;) N
      • Computer Science
        • Terminology and Concepts
        • Network
        • Operating System
        • Database
        • Data Structure
      • Frontend
        • Javascript Essentials
        • Perfomance Optimization
        • JS Patterns
        • Next.js
        • Flutter
      • Backend
        • Node.js
      • DevOps
        • Docker & Kubernetes
      • Coding Test N
        • LeetCode N
        • Programmers
      • Tech Books & Lectures
        • Javascript_Modern JS Deep d..
        • Network_IT 엔지니어를 위한 네트워크 입문
      • Projects
        • PolyLingo_2025
        • Build Your Body_2024
        • JStargram_2021
        • Covid19 Tracker_2021
        • JPortfolio_2021
      • BootCamp_Codestates
        • TIL
        • TILookCloser
        • Pre Tech Blog
        • IM Tech Blog
        • Daily Issues and DeBugging
        • First Project
        • Final Project
        • Sprint Review
        • Good to Know
        • Socrative Review
        • HTML & CSS
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 글쓰기
    • 관리
  • 공지사항

  • 인기 글

  • 태그

    structure of os
    VoiceJournal
    Data Structure
    자바스크립트 딥다이브
    자바스크립트
    이벤트
    mobile app
    indie hacker
    TCP/IP
    딥다이브
    프론트엔드 성능 최적화 가이드
    DOM
    스코프
    커리어
    Operating System
    Network
    모던 자바스크립트 Deep Dive
    js pattern
    CPU scheduling algorithm
    How memory manage data
    polylingo
    JavaScript
    leetcode
    database
    testing
    Threads and Multithreading
    need a database
    Shared resources
    Time complexity and Space complexity
    Binary Tree BFS
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
JTB
3일차 파이어베이스 로그인/로그아웃 및 채팅 구현
상단으로

티스토리툴바