20240710 카카오 로그인, zustand

RingKim1·2024년 7월 11일

TIL

목록 보기
50/77
post-thumbnail

Today

1. 정리

2. Next.js 심화 강의

  • SSG 서버 컴포넌트에서 route handler 호출은 빌드 실패의 원인
  • Tanstack Query with Next.js 패턴: prefetching, dehydrate, and hydrate
  • parallel route 를 이용한 대시보드 UI
  • intercepting route 를 이용한 모달 핸들링

3. 프로젝트

소셜 로그인 기능

재사용성을 위해 커스텀 훅으로 정리
까까오대화인 이유는 컨셉이 레트로..

코드

"use client";

import React from "react";
import { createClient } from "@/supabase/client";
import { useRouter } from "next/navigation";
import useAuthStore from "@/zustand/authStore";

const useKakao = () => {
  const supabase = createClient();
  const router = useRouter();
  const { clearAuth } = useAuthStore();

  // 로그인
  const signInWithKakao = async () => {
    const { data, error } = await supabase.auth.signInWithOAuth({
      provider: "kakao",
      options: {
        queryParams: { access_type: "offline", prompt: "select_account" },
        redirectTo: `http://localhost:3000/api/auth/callback/`
      }
    });
  };

  // 로그아웃
  const signOut = async () => {
    const { error } = await supabase.auth.signOut();
    clearAuth();
    alert("로그아웃 되었습니다.");
    router.push("/login");
  };

  return { signInWithKakao, signOut };
};

export default useKakao;

🔗 슈퍼베이스 활용 카카오 간편 로그인 구현

zustand

로그인 전역 상태 관리를 위해 도입!
처음에는 공식문서를 바탕으로 코드를 작성했다가 확장성이 있는 형태로 변경
(로그인 상태뿐만 아니라 유저 정보, 토큰등을 저장 해도 사용 가능하도록)

import { create } from "zustand";

type UserInfo = {
  id: string;
  email: string;
};

type State = {
  isAuthenticated: boolean;
  userInfo: UserInfo | null;
  // token: string | null;
};

type Actions = {
  // setAuth: (token: string, user: User) => void;
  setAuth: (userInfo: UserInfo) => void;
  clearAuth: () => void;
  setIsAuthenticated: (status: boolean) => void;
};

const initialState: State = {
  isAuthenticated: false,
  userInfo: null
  // token: null
};

const useAuthStore = create<State & Actions>((set) => ({
  ...initialState,
  // setAuth: (token, user) => set({ isAuthenticated: true, token, user }),
  // clearAuth: () => set({ isAuthenticated: false, token: null, user: null }),
  setAuth: (userInfo) => set({ userInfo }),
  clearAuth: () => set({ isAuthenticated: false, userInfo: null }),
  setIsAuthenticated: (status) => set({ isAuthenticated: status })
}));

export default useAuthStore;

Learn

TroubleShooting

문제

카카오 로그인 기능을 구현하는데 있어서 공식문서에서 말한대로 routehandler로 리다이렉트를 했는데 계속 오류가 발생

원인

서로 다른 클라이언트 생성 사용

해결

기존
클라이언트 사이드 애플리케이션(브라우저)에서 사용

변경

  • 서버 사이드 렌더링(SSR) 환경에서 브라우저 클라이언트를 생성할 때 사용
  • Next.js와 같은 SSR 프레임워크에서 사용

소셜 로그인 기능이 구현될지 몰랐지만 성공은 했다. 공식문서는 위대하다

zustand는 확실히 프로젝트 세팅 등 편리하고
redux보다 사용하기 쉽다.
생소해서 겁을 먹었을 뿐..!


주절주절

오늘도 무엇인가 배워가긴 하는데 그것을 나중에도 써먹을 수 있도록 정리를 잘 해야하는데...
내 velog 임시저장에는 아직 정리들이 글들이 산더미

사실 notion에는 더 많음

profile
커피는 콜드브루

0개의 댓글