bernabe9 / redux-react-session

:key: Simple Session API storage for Redux and React
https://bernabe9.github.io/redux-react-session/
147 stars 41 forks source link

React Router4 - Alternative of OnEnter #14

Closed dipesh008 closed 7 years ago

dipesh008 commented 7 years ago

Hi, I am unable to figure out how to put restrictions on private routes. In React Router4, onEnter is removed.

Store listener is not working as the event (@@redux-react-session/GET_SESSION_SUCCESS) is ASYNC.

How to check if the user is authenticated.

@bernabe9 Any help on this is appreciated.

Thank you in Advance.

bernabe9 commented 7 years ago

Hi @dipesh008, Here is a simple example using an alternative of OnEnter with async authorization and redux-react-session: https://github.com/bernabe9/react-router-v4-auth-example

Check out this component PrivateRoute: https://github.com/bernabe9/redux-react-session/blob/master/examples/react-router-v4-example/src/components/PrivateRoute.js

The PrivateRoute component receive a prop authenticated, and then in the render prop of the Route component you can choose what to do depending on the the authenticated prop value.

const PrivateRoute = ({ component, exact = false, path, authenticated }) => (
  <Route
    exact={exact}
    path={path}
    render={props => (
      authenticated ? (
        React.createElement(component, props)
      ) : (
        <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }}/>
      )
    )}
  />
);

Hope this helps!

dipesh008 commented 7 years ago

@bernabe9

Thanks for the quick response. I checked this example and tried. But the problem is react-redux-session fetches session into store ASYNC way. so I am not getting the value of authenticated true the first time.

bernabe9 commented 7 years ago

I know that react-redux-session fetches the session in an async way, for that it provides the flag checked to check if the session was already fetched.

Here is how it is used in the App component:

const App = ({ authenticated, checked }) => (
  <Router>
    { checked &&
      <div>
        <PrivateRoute exact path="/" component={Home} authenticated={authenticated}/>
        <Route path="/login" component={Login}/>
      </div>
    }
  </Router>
);

So, the first time that PrivateRoute is rendered the session was already fetched and you are sure that the value of authenticated is the real value.

dipesh008 commented 7 years ago

Thank you @bernabe9

Now it is clear why checked is added. If we can add this to the document, it will help others too.