javascriptreactjsauthenticationreact-routerreact-hoc

React Authentication using HOC


The server sends a 401 response if the user is not authenticated and I was trying to check for authentication in the front end using a HOC as seen in Performing Authentication on Routes with react-router-v4. However, I am getting an error saying TypeError: Cannot read property 'Component' of undefined in RequireAuth

RequireAuth.js

import {React} from 'react'
import {Redirect} from 'react-router-dom'

const RequireAuth = (Component) => { 

    return class Apps extends React.Component { 
        state = {
            isAuthenticated: false,
            isLoading: true
        }

        async componentDidMount() {
            const url = '/getinfo'
            const json = await fetch(url, {method: 'GET'})
            if (json.status !== 401)    
                this.setState({isAuthenticated: true, isLoading: false})
            else
                console.log('not auth!')
        } 

        render() { 
           const { isAuthenticated, isLoading } = this.state;
           if(isLoading) {
               return <div>Loading...</div>
           }
           if(!isAuthenticated) {
               return <Redirect to="/" />
           }
           return <Component {...this.props} /> 
        }
    } 

} 

export { RequireAuth }

App.js

import React from 'react';
import { BrowserRouter as Router, Route, Switch, withRouter } from 'react-router-dom';
import SignIn from './SignIn'
import NavigationBar from './NavigationBar'
import LandingPage from './LandingPage'
import Profile from './Profile'
import Register from './Register'
import { RequireAuth } from './RequireAuth'

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() { 
  return (
    <div>
      <Router>
            <NavigationBar />
            <Switch>
              <Route exact path = '/'
                component = {LandingPage}
              />
              <Route exact path = '/register'
                component = {Register}
              />
              <Route exact path = '/profile' 
                component = {RequireAuth(Profile)}
              />
              <Route path="*" component = {() => "404 NOT FOUND"}/>
            </Switch>
      </Router>
    </div>
  );
}
}

export default withRouter(App);


Solution

  • I can think of some possibilities:

    ------- Moved this to top which eventually fixed OP's issue -------

    1. Try remove the curly braces at {React},
    import React from 'react';
    

    ------- Moved this to top which eventually fixed OP's issue -------


    1. In RequireAuth.js, Try
    const RequireAuth = ({ Component }) => {} // changed from Component to { Component }
    

    In App.js, use Component start with capital letter

    <Route exact path = '/' Component = {LandingPage}/>
    
    

    1. Also, in <Route path="*" component = {() => "404 NOT FOUND"}/>, looks like you're not passing in a React component because the function is not returning a JSX (I can't test now so I'm not very sure, though).

    try this instead:

    () => <div>404 NOT FOUND</div>
    

    or if it doesn't work, define a functional component externally and pass into the Route:

    const NotFoundComponent = () => <div>404 NOT FOUND</div>
    
    <Route path="*" component = {NotFoundComponent}/>