3'''' Sử dụng history để chuyển đăng nhập thành công sang trang chủ và thất bại có thông báo :) (ok)

C:\Users\Administrator\Desktop\app\src\Routes\HomeRoutes.tsx

import React, {Component} from "react";
import { Switch, Route } from "react-router-dom";
import Home from "./../pages/Home";
import AuthenticatedGuard from './../guards/AuthenticatedGuard';
function HomeRoutes() {
	return (
		<Switch>
			<AuthenticatedGuard exact path="/" component={Home} />
		</Switch>
	)
}
export default HomeRoutes;

C:\Users\Administrator\Desktop\app\src\pages\Login\index.tsx

import React, { useState } from "react";
import { login } from './../../middlewares/thunks';
import { connect } from 'react-redux';
import { useHistory } from "react-router-dom";
import { PATH } from "./../../constants/paths";
import * as interfaces from './../../interface';
const Login = (props: any) => {
  const [username, setName] = useState('');
  const [password, setPass] = useState('');
  const [error, setError] = useState('');
  const { login } = props;
  const history = useHistory();
  const handleUsername = (event: React.ChangeEvent < HTMLInputElement > ) => {
    var { value } = event.target;
    setName(value);
  }
  const handlePassword = (event: React.ChangeEvent < HTMLInputElement > ) => {
    var { value } = event.target;
    setPass(value);
  }
  const onSubmitForm = (event: React.FormEvent < HTMLFormElement > ) => {
    event.preventDefault();
    const payload = { username, password };
    login(payload)
    .then((res: interfaces.resLogin) => {
      history.push(PATH.HOME)
    })
    .catch((err:interfaces.errLogin) => {
      setError(err.payload)
    })
  }
  return (
    <div className="container space-2 space-0--lg mt-lg-8 mt-5">
      <div className="row justify-content-lg-center align-items-lg-center">
        <div className="col-lg-5">
          <div className="bg-white shadow-sm rounded p-4 border">
            <form onSubmit={onSubmitForm}>
              <div className="mb-4 text-center">
                <h2 className="h2">Login</h2>
                <p>Lorem, ipsum dolor sit amet. &nbsp;😊</p>
              </div>
              <div className="js-form-message mb-3">
                <div className="js-focus-state input-group input-group form">
                  <input type="text" className="form-control form__input" name="username" value={username}  placeholder="Enter your username" onChange={handleUsername} />
                </div>
              </div>
              <div className="js-form-message mb-3">
                <div className="js-focus-state input-group input-group form">
                  <input type="password" className="form-control form__input" name="password" placeholder="Enter your password" onChange={handlePassword}/>
                </div>
              </div>
              {error && (
                <div className="mb-3 text-danger text-xl-center">{error}</div>
              )}
              <button type="submit" className="btn btn-block btn-primary">Đăng nhập</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  )
}
const mapStateToProps = (state: any) => ({

});
const mapDispatchToProps = {
  login
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);

C:\Users\Administrator\Desktop\app\src\apis\user.tsx

import * as interfaces from './../interface';
export const loginApi = ({ username, password }: interfaces.ReqLogin): any =>
new Promise((resolve, reject) => {
  setTimeout(() => {
    if (username === 'admin' && password === '123') {
      resolve({
        payload: { 
          access_token: '82jdu82193yh90sad83hxfgsd'
        },
        message: 'Login thành công'
      })
    } else {
      reject('Login thất bại')
    }
  }, 100)
});

C:\Users\Administrator\Desktop\app\src\interface\index.tsx

import { RouteProps } from "react-router-dom";
export interface ReqLogin {
  username: string
  password: string
}
export interface Res {
  data: any
  message: string
}
export interface ResLoginApi extends Res {
  data: {
    access_token: string
  }
}
export interface resLogin {
  type: string;
  payload: {
    access_token: string,
    message : string
  }
}
export interface errLogin {
  type: string
  payload: string
}
export interface AuthenProps {
	isAuthenticated: boolean
}
export interface Props  extends AuthenProps, RouteProps {
}
export interface StateProps {
	app: {
		isAuthenticated: boolean
	}
}

C:\Users\Administrator\Desktop\app\src\guards\AuthenticatedGuard\index.tsx

import React from 'react';
import { Route, RouteProps, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import * as interfaces from './../../interface';
function AuthenticatedGuard(props: any) {
  const { isAuthenticated, component: Component, ...rest } = props;
  return (
    <Route
    	{...rest}
      render = { props => {
      	if (!isAuthenticated && !localStorage.getItem("token")) {
        	return <Redirect to="/login" />
        }
        return <Component {...props}/>
      }}
    />
  )
}
const mapStateToProps = (state: any) => ({
  isAuthenticated: state.app.isAuthenticated
})
const mapDispatchToProps = {

}
export default connect(mapStateToProps, mapDispatchToProps)(AuthenticatedGuard);

C:\Users\Administrator\Desktop\app\src\constants\paths.tsx

export const PATH = {
	HOME: "/",
	LOGIN: "/login",
	PRODUCT: "/product",
}

Last updated

Was this helpful?