0

I have tried to create an authenticated route component to wrap my react routes which redirects to '/' path if login is not valid. I was following this answer: https://stackoverflow.com/a/43171515/6716062

However I would like to access my redux store. How can I access the loginStatus prop which I want to inject into props? With the following code props.loginStatus is undefined

Thanks

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { SUCCESS } from '../common/webUtils';
import { connect } from 'react-redux';

function AuthRoute( {component: Component, ...rest} ) {
  return (
    <Route
      {...rest}
      render={ (props) => props.loginStatus === SUCCESS
      ? <Component {...props} />
      : <Redirect to={{pathname: '/', state: {from: props.location}}} />}
  />
  )
}

function mapStateToProps( state ) {
  return {
    loginStatus: state.userReducer.loginStatus
  }
}

export default connect( mapStateToProps )( AuthRoute ); 
Tamjid
  • 974
  • 2
  • 7
  • 20
  • `loginStatus` is not being passed in `AuthRoute` props. It should work if you add it. – alewis729 Jun 10 '20 at 03:09
  • 1
    You can use selectors to access the props from redux store, but you need to pass them as mentioned by @alewis729 – Mohit Jun 10 '20 at 04:29

1 Answers1

0

Access loginStatus from the correct props object, in this case rest, contains the loginStatus prop passed from the connect HOC. You can also factor the code a bit to do the check outside what is being returned. Route only passes the route-props to component, render, or children.

function AuthRoute( {component: Component, loginStatus, ...rest} ) {
  const authenticated = loginStatus === SUCCESS;
  return (
    <Route
      {...rest}
      render={(routeProps) => authenticated
        ? <Component {...routeProps} />
        : <Redirect to={{pathname: '/', state: {from: props.location}}} />
      }
  />
  )
}

function mapStateToProps( state ) {
  return {
    loginStatus: state.userReducer.loginStatus
  }
}

export default connect( mapStateToProps )( AuthRoute );
Drew Reese
  • 43,833
  • 5
  • 21
  • 43