[22.11.23] TIL +17

김미영·2022년 11월 23일
0

내배캠

목록 보기
33/46

기초프로젝트 진행중..죽을거같..지만 많은것을 배웠다.

오늘 배운것 및 느낀점을 나열해보고자 한다.

  • 안될때는 의심가는곳에 콘솔 찍어보기
  • 로그아웃 함수
export const logout = (event) => {
  event.preventDefault(); // a태그가 가지고있는 새로고침하는 기본 이벤트를 없애줌
  console.log('로그아웃클릭');
  signOut(authService)
    .then(() => {
      // Sign-out successful.
      localStorage.clear();
      console.log('로그아웃 성공');
    })
    .catch((error) => {
      // An error happened.
      console.log('error:', error);
    });
};
  • a태그는 기본적으로 누르면 새로고침을 하는 기능이 내장되어 있다.
    a태그를 누를 때 무언가를 실행하고 싶다면, 매개변수로 event를 넣어주고 'event.preventDefault();' 문구를 추가해준다.
    그럼 새로고침을 하지 않는다.

  • firebase.js 파일을 만들어주고 거기에 sdk를 연결해주었다.
    그곳에 initializeApp(firebaseConfig)를 app이라는 함수에 담아 다른 함수에서도 사용할 수 있게 구성해주었다.

export const app = initializeApp(firebaseConfig);
export const dbService = getFirestore(app);
export const authService = getAuth(app);
export const storageService = getStorage(app);
  • 이제 여기서 authService.currentUser 를 확인해야되는데, 이것이 뭐냐?
    로그인 되어있다면 로그인 된 유저의 정보를 말한다. 콘솔로 찍으면 별의별 정보가 다 나온다.

  • 근데 오늘 그 authService.cureentUser를 찍어도 정보가 나오지 않았는데, 그때의 코드를 적어보겠다.

  if (path === 'mypage') {

    document.getElementById('profileView').src =
      authService.currentUser.photoURL ?? '../assets/mypageimg.png';
    document.getElementById('profileNickname').placeholder =
      authService.currentUser.displayName ?? '닉네임 없음';
    document.getElementById('profileEmail').placeholder =
      authService.currentUser.email;
  }
};
  • 대충 이 코드이다. 해석을 해보자면,
    지금 현재 해쉬태그(path=해쉬태그)가 mypage 라면,
    유저정보의 photoURL이 있으면, 그걸 쓰고, 없으면 기본이미지로 사용해라/
    유저정보의 displayName이 있으면 그걸 쓰고, 없으면 닉네임없음 이라는 문구를 플레이스홀더에 적어라./
    등등..뭐 이메일도 마찬가지.

  • 근데 이 코드 실행이 안됐었다. 왜일까?

  • 서버 통신은 비동기이다. 비동기의 특징은 먼저 동기 프로그램부터 실행하고 비동기를 실행한다.
    그 이유는 브라우저 엔진, 자바스크립트 엔진이 비동기 실행되기 전 먼저 읽어오기 때문이다.
    근데 비동기 프로그램을 먼저 실행하려고 하니 정상적으로 동작이 안됐던것이다.
    해결 방법은 아래와 같다.

  if (path === 'mypage') {

    document.getElementById('profileView').src =
      authService.currentUser?.photoURL ?? '../assets/mypageimg.png';
    document.getElementById('profileNickname').placeholder =
      authService.currentUser?.displayName ?? '닉네임 없음';
    document.getElementById('profileEmail').placeholder =
      authService.currentUser?.email;
  }
};
  • 물음표 하나씩 추가해줬다.
    authService.currentUser 는 비동기이기 때문에 끝에 ?를 붙혀주면, null일 때 신경쓰지 말고 데이터가 있을 때만 신경쓰라는 뜻의 코드이다.
  • 로그인/ 비로그인 시 버튼 클릭했을 때 나오는 메뉴 다르게 하기
    이거는 튜터님 도움을 안받고 혼자 구현해보았다.
if (user) {
      console.log('로그인상태')
      const topProfile = document.querySelector('#nav_profile');
      const menuDisplay = document.querySelector('#menu_display');
      const navProfileImg = document.querySelector('#nav_profile_img');
      topProfile.addEventListener('click', function () {
        menuDisplay.style.display = 'block';
      });
      document.getElementById('nav_profile_img').src =
        authService.currentUser.photoURL ?? '../assets/mypageimg.png';
      // 다른 영역 클릭 시 메뉴 없어짐
      document.addEventListener('click', function (event) {
        if (event.target != navProfileImg) {
          menuDisplay.style.display = 'none';
        }
      });
    } else {
      console.log('로그아웃상태')
      const topProfile = document.querySelector('#nav_profile');
      const menuDisplay = document.querySelector('#menu_display');
      const navProfileImg = document.querySelector('#nav_profile_img');
      const logoutMenu = document.getElementById('profile-menu-logout');
      const menuDisplayLogOut = document.getElementById('menu_display-logout');
      menuDisplay.style.display = 'none';
      topProfile.addEventListener('click', function () {
        console.log('menuDisplayLogOut', menuDisplayLogOut);
        menuDisplayLogOut.style.display = 'block';
      });
      // 다른 영역 클릭 시 메뉴 없어짐
      document.addEventListener('click', function (event) {
        
        if (event.target != navProfileImg) {
          console.log('다른영역');
          menuDisplayLogOut.style.display = 'none';
        }
      });

    }
  });
  • 이렇게, 동일한 메뉴를 두개를 만들어놓고 안에 text만 변경해주었는데,
    로그인 시 버튼 클릭하면 menuDisplay를 보여주고,
    비로그인 시 버튼 클릭하면 menuDisplayLogOut 을 보여주는 코드이다.
    시행착오가 조금 있긴 했지만 잘 구성을 했다.
    근데 돔이 들어간 변수들은 if랑 else 따로 적용이 되는지 오류가 나길래 각각 넣어줬다.
    자바스크립트 공부를 더 해야될 것 같다 ㅠㅠ 파이어베이스에 사용되는 문법 뭐가뭔지 이해가 안된다..
profile
프론트엔드 지망생

1개의 댓글

comment-user-thumbnail
2022년 11월 24일

감정이 고스란히 느껴지는 글이네요 ㅎㅎ
고생 진짜 많으셨어요
지금은 모든게 연결되지 않더라도 어느순간 다 합쳐지는 순간이 오실겁니다!!

답글 달기