0

I have a this.props.auth reducer in my protected route (returns user if authenticated or false when not). Currently I'm checking that if this.props.auth is false or has a user inside of it. When false, then redirect to /login or if true, render the page with this.props.auth data. I currently have to rewrite the auth logic for all components same way. What would be the best way to make the is user authenticated check reusable?

Protected Component Code:

class StaffMeetingsPage extends React.Component {
componentDidMount() {
    document.title = "Staff Meetings";
}

renderContent() {
    console.log(this.props.auth)
    switch (this.props.auth) {
        case null:
            return 'still fetching';
        case false:
            return this.props.history.push('/login');;
        default:
            return <div>Logged in</div>;
    }
}

render() {
    console.log(this.props);
    return(
        <div>
            {this.renderContent()}
        </div>
    );
  }
}

function mapStateToProps(state) {
    return {
        auth: state.authenticationProperty
    };
}

export default connect(mapStateToProps)(StaffMeetingsPage);

Console logging this.props.auth when logged in:

email: "[email protected]" username: "user" _id: "adasdasdasfe3453" __proto__: Object

Console logging this.props.auth when not logged in:

false

1 Answer 1

3

I usually create a PrivateRoute component that checks if the user is logged in (via prop, redux, localstorage or something).

Something like:

import { Route, Redirect } from 'react-router-dom'

const PrivateRoute = ({ isLoggedIn, ...props }) =>
  isLoggedIn
    ? <Route { ...props } />
    : <Redirect to="/login" />

In your case you could connect this PrivateRoute component to the part of your state where you handle the authentication:

function mapStateToProps(state) {
    return {
        isLoggedIn: !!state.authenticationProperty
    };
}

export default connect(mapStateToProps)(PrivateRoute)

In the router I then use it for my, well, private routes :)

<Switch>
  <PrivateRoute path="/staff-meetings" component={StaffMeetingsPage} />
  <Route path="/login" component={Login}/>
</Switch>
Sign up to request clarification or add additional context in comments.

1 Comment

my redux reducer action is async, how can i wait for that result in PrivateRoute?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.