Kush Khanna
Kush Khanna

Reputation: 19

Routes not working as desired in React JS

I am trying to build a full stack application with User login/logout functionality.

I want to protect certain pages such that they can only be viewed when the user is logged in. For login I have created a REST API and I am using session storage to keep track of whether the user is logged in or not.

validateUser = () => {

        let user = { 

            username: this.state.email, 
            password: this.state.password,
            //status: "LOGGED_IN"
        };
        
        UserService.authenticateUser(user).then((res) => {
            if(res.data === 'SUCCESS') {
                window.sessionStorage.setItem("isUserLogged", true);

      
            } else if(res.data === 'FAILURE') {
                window.sessionStorage.setItem("isUserLogged", false);
                this.resetLoginForm();
                this.setState({"error":"Invalid username or password"});
            }
        })
    };

Tis is my App.js

function App() {


  return (

    <div>
      <Router>
          <HeaderComponent/>
          <div className="container">
            <Switch> 
              <Route path="/" exact component={LandingPageComponent}></Route>
              {/* <Route path ="/customers" component = {ListCustomerComponent}></Route> */}
              {/* <Route path ="/add-customer/:id" component = {CreateCustomerComponent}></Route> */}
              <Route path = "/view-customer/:id" component = {ViewCustomerComponent}></Route>
              <Route path = "/admin-login" component = {AdminLoginComponent}></Route>
              <Route path = "/admin-register" component = {AdminResgisterComponent}></Route>

              <Route path="/customers" exact render={() => (
                window.sessionStorage.getItem("isUserLogged") === "true"
                ? <ListCustomerComponent />
                : <Redirect to='/admin-login' />
              )} />

              <Route path="/add-customer/:id" exact render={() => (
                window.sessionStorage.getItem("isUserLogged") === "true"
                ? <CreateCustomerComponent />
                : <Redirect to='/admin-login' />
              )} />

              
            </Switch>
          </div>
          <FooterComponent/>
      </Router>
    </div>
  );
} 

export default App;

Everything works fine if I don't check my session storage. But when I try to implement the conditional routes as shown above I start getting errors.

Error

If I just put simple routes, then I don't encounter this error.

Any help would be highly appreciated.

Upvotes: 0

Views: 53

Answers (3)

Muhammed THANSEER
Muhammed THANSEER

Reputation: 41

 <Switch>
    {/* Login Sections goes Here */}
    <Route exact path='/' component={MainPage} />
    <Route exact path='/login' component={Login} />
    <Route exact path='/admin/' component={LoginAdmin} />
    <Route exact path='/register' component={Register} />

    {/* AdminUser ROutes goes here */}
    <SuperUserDashboard>
      <Route exact path='/admin/dashboard' component={Dashboardpage} />
      <Route exact path='/admin/users' component={UsersAdmin} />
    </SuperUserDashboard>

    <Route exact path='' component={Notfound} />
  </Switch>

in superuser dashboard check if user is authenticated if not redirect to admin login page else all the routes will be visible

Upvotes: 0

Hadi KAR
Hadi KAR

Reputation: 464

You didn't show what you did on ListCustomerComponent. You could try to encapsulate your component using HOC withRouter or if you are using Functional component, use useHistory hook.

// on export class component

export default withRouter(YourComponent)

in functional component, you can use

const YourComponent = ()=>{
  
  const history = useHistory();
  // then you can say something such as
  // history.push(...)

  return <>...your view here...</>
}


export default YourComponent;

Upvotes: 0

Hải B&#249;i
Hải B&#249;i

Reputation: 2931

You didn't pass Route props into your component. So history does not included in props, you can console.log(this.props) to check what this.props contains.

To fix it, let's pass Route props into your components

<Route path="/add-customer/:id" exact render={(props) => (
   window.sessionStorage.getItem("isUserLogged") === "true"
   ? <CreateCustomerComponent {...props} /> // ADD PROPS HERE
   : <Redirect to='/admin-login' />
} />

Upvotes: 1

Related Questions