tryingtodevelop
tryingtodevelop

Reputation: 11

How can i check if user is authenticated more efficently in react?

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

Upvotes: 0

Views: 7415

Answers (1)

0xc14m1z
0xc14m1z

Reputation: 3725

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>

Upvotes: 3

Related Questions