M
M
m_frost2019-06-04 15:39:17
React
m_frost, 2019-06-04 15:39:17

How to properly implement PrivateRoute???

Krch such a question is PrivateRoute which checks in the redux store whether there is a login user in the system, I fetch the user by tokenau from the local storage and by default it is null and after the fetch if it is successful the user appears in the system. The problem is that while the fetch of the PrivateRoute user is being processed, the user is already being redirected as not logged in. It’s up to me to decide how to asynchronously check the user has already fetched and if not, then redirects, but my knowledge is not enough to solve this, maybe some of you have already encountered something similar (do not offer cookies).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-04
@m_frost

For example:

const PrivateRoute = ({ component: Component, render, isSignedIn, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      if (!isSignedIn) return (
        <Redirect
          to={{
            pathname: '/login',
            state: { referrer: props.history.location.pathname },
          }}
        />
      );

      if (render) return render({ ...props });

      return <Component {...props} />;
    }}
  />
);

const mapStateToProps = (state) => ({
  isSignedIn: isSignedInSelector(state),
});

export default connect(mapStateToProps)(PrivateRoute);

referrer is passed here to be able to return to the landing page after login.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question