4. 1 Xây dựng AuthenticatedGuard (ok)

C:\Users\Administrator\Desktop\start\src\routes\HomeRoutes.tsx

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

C:\Users\Administrator\Desktop\start\src\guards\AuthenticatedGuard.tsx

import React, { Component } from 'react';
import { Route, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import * as interfaces from './../interface';
function AuthenticatedGuard(props: interfaces.Props) {
  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: false
})
const mapDispatchToProps = (dispatch: any) => ({
})
export default connect(mapStateToProps, mapDispatchToProps)(AuthenticatedGuard);

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

import { RouteProps, RouteComponentProps } from 'react-router-dom';
export interface ReduxProps {
  isAuthenticated: boolean
}
export interface Props extends ReduxProps, RouteProps {
  component: React.ComponentType < RouteComponentProps >
}

Last updated

Was this helpful?