ファランクス by ponta

Supabase : メールアドレスログイン

** GoogleおよびDiscordログインは普通に進めればlocalhostのみで機能する 調べてもわからず

メールアドレスログイン

ベース

"use client";
import { useEffect, useState } from "react";
import Login from "./Login";
import { supabase } from "@/lib/supabaseClient";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { useRouter } from "next/navigation";

const EmailAuthcomponents = () => {
  const router = useRouter();

  const [currentUser, setcurrentUser] = useState("");
  const logout = async () => {
    const { error } = await supabase.auth.signOut();
    router.push("/");
  };
  const getCurrentUser = async () => {
    const { data } = await supabase.auth.getSession();
    if (data.session !== null) {
      const {
        data: { user },
      } = await supabase.auth.getUser();
      setcurrentUser(user.email);
    }
  };
  useEffect(() => {
    getCurrentUser();
  }, []);

  return (
    <>
      <br />
      {currentUser ? (
        <div>
          ユーザー:{currentUser}
          <Button onClick={logout}>ログアウト</Button>
        </div>
      ) : (
        <div suppressHydrationWarning={true}>
          ログイン
          <Login />
        </div>
      )}
      <div>
        <Button variant="outline">
          <Link href="/signup">登録する</Link>
        </Button>
        <Button variant="outline">
          <Link href="/password-resset">パスワードを忘れた場合</Link>
        </Button>
      </div>
    </>
  );
};

export default EmailAuthcomponents;
  • コンポーネントは機能ごとにわける
  • 遷移URLも増やした方がわかりやすい . 例 : 登録用ページやダッシュボード

useRouter

クリックせずに遷移=リダイレクトができる

注** next/router でインポートするとエラーになる

jsxで場合分け

{ condition ? ログイン時 : ログアウト時 }

ログイン状況によりコンポーネントの表示/非表示を決める

user情報取得のテンプレート

const user = supabase.auth.getUser();

← Go home