3

I have this URL: /user/Jd5Egbh... I use react-router-dom for navigation. I have made a UserDetails component. I use mapStateToProps to get url params like this:

function mapStateToProps({ users }, ownProps) {
   return { user: users[ownProps.match.params.uid]};
}

It works fine but I would like to protect this route and allow access only for authenticated users.

In other components, I use a withAuthorization component and compose from recomposing to protect the route.

I tried to combine these two features like below:

export default compose(
  withAuthorization(authCondition),
  connect(mapStateToProps, { fetchUser })
)(UserDetails);

But ownProps is undefined in mapStateToProps function

How can I access URL params if I use compose to protect route?

EDIT1:

import React from 'react';
import { connect } from 'react-redux';
import { compose } from 'recompose';
import { withRouter } from 'react-router-dom';

import { firebase, db, auth } from '../firebase';

const withAuthorization = (condition) => (Component) => {
  class WithAuthorization extends React.Component {
    componentDidMount() {
      firebase.auth.onAuthStateChanged(authUser => {
        if (!condition(authUser)) {
          this.props.history.push('/');
        } else {
          db.onceGetUser(authUser.uid).then(snapshot => {
              let user_data = snapshot.val();
              if (!user_data.admin) {
                auth.doSignOut();
              }
          });
        }
      });
    }

    render() {
      return this.props.authUser ? <Component /> : null;
    }
  }

  const mapStateToProps = (state) => ({
    authUser: state.auth.authUser,
  });

  return compose(
    withRouter,
    connect(mapStateToProps),
  )(WithAuthorization);
}

export default withAuthorization;

0 Answers0