0
0

Reactアプリのセットアップ ~ 簡単な認証まで

Last updated at Posted at 2024-08-26

voltaを使ってReactアプリケーションをset upするところまでやったので、記録を残す。認証はfirebaseを使っている。

  1. voltaのインストールは公式サイトを参考。めちゃ簡単。

  2. npx create-react-app --template typescript my-app-tsでtypescript templateを使用して、reactアプリケーションを立ち上げる。

  3. volta pin npm@10.8.2volta pin node@20.17.0とかで、package.jsonに指定バージョンのnpmとnodeを使うことを書いてくれる。他のメンバーは、npm iするだけ!

  4. firebaseのプロジェクト作成してreactアプリと繋げる。詳細は公式document。プロジェクト作成して、言われた通りにセットアップするだけ

  5. ログイン機能いざ実装!

    • App.tsxはこんな感じ
    import { LoginForm } from "./LoginForm";
    import AuthRouteGuard from "./AuthRouteGuard";
    
    function App() {
      return (
        <>
          <LoginForm />
          <AuthRouteGuard>
            <Contents />
          </AuthRouteGuard>
        </>
      )
    }
    
    const Contents = () => {
      return (
        <p>sign in済み</p>
      )
    }
    
    export default App;
    
    • AuthRouteGuardはこんな感じ
    import { FC, ReactNode } from 'react'
    
    import { useAuth } from './query/useAuth'
    
    const AuthRouteGuardComponent: FC<{
      children: ReactNode
    }> = (props) => {
      const { children } = props
    
      const { loading, error } = useAuth()
    
      if (loading) {
        return <p>Loading中だよ</p>
      }
    
      if (error) {
        console.log(error)
        return null
      }
    
      return <>{children}</>
    }
    
    const AuthRouteGuard: FC<{
      children: ReactNode
    }> = (props) => {
      const { children } = props
          return <AuthRouteGuardComponent>{children}</AuthRouteGuardComponent>
        }
    
    export default AuthRouteGuard
    
    • useAuthはこんな感じ
import { onAuthStateChanged, User } from 'firebase/auth';
import { useState, useEffect } from 'react';

import { fireAuth } from '../firebase';

export const useAuth = () => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(fireAuth, async (user) => {
      if (user) {
        setUser(user);
      } else {
        setUser(null);
      }
      setLoading(false);
    });

    return () => unsubscribe();
  }, []);

  if (loading) {
    return {
      user: null,
      error: null,
      loading: true as const,
    };
  }

  if (!user) {
    return {
      user: null,
      error: "unauthorized",
      loading: false as const,
    };
  }

  return {
    user: user,
    error: null,
    loading: false as const,
  };
};

AuthRouteGuard componentがユーザーが認証済みかを判定して、そうじゃなければ弾いてくれる。
認証だけfirebaseを使うなら、MeRouteGuardとかを別で用意してそこで、DBからユーザー情報が正しく返ってくるかどうかの判定を行う。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0