7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React Hooks + router + TypeScript + Firebaseでログイン認証画面

Last updated at Posted at 2019-10-12

React16.8のHooksについて

ReactはClassよりFunctionComponentのほうがコード少なくて好きやけどstateが使えなかったが、
いつのまにか使えるようになってたのでログイン画面を置き換えてみたらスッキリした

#できあがり

App.tsx
import React, { useState, useEffect } from 'react';
import {
  BrowserRouter, Route, Switch, Redirect,
} from 'react-router-dom';
import { LinearProgress } from '@material-ui/core';
import SignIn from './pages/signin';
import SignUp from './pages/signup';
import Dashboard from './pages/dashboard';
import firebase from './components/firebase';
import './App.css';

type FirebaseUser = firebase.User|null

const App:React.FC = () => {
  const [authUser, setAuthUser] = useState<FirebaseUser>(null);
  useEffect(() => {
    firebase.auth().onAuthStateChanged((user) => {
      setAuthUser(user);
    });
  });
  return (
    <BrowserRouter>
      <div className="App">
        <Switch>
          <Route exact path="/signin" render={() => <SignIn authUser={(user:FirebaseUser) => setAuthUser(user)} />} />
          <Route exact path="/signup" component={SignUp} />
          <Route exact path="/" component={authUser ? Dashboard : LinearProgress} />
          <Route render={() => <Redirect to="/signin" />} />
        </Switch>
      </div>
    </BrowserRouter>
  );
};

useState

this.state,setStateの置き換え。

認証済みなら更新されたauthUserを元にログイン認証先に遷移できるようになる。

useEffect

componentDidMount,componentDidUpdate,componentWillUnmount の置き換え。
ここでfirebase.auth().onAuthStateChanged()を呼び出しauthUserが更新される。

7
4
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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?