Balaji Rajendran
Balaji Rajendran

Reputation: 367

TypeError: Object(...) is not a function - Can't connect redux with wrapper function in react

for Auth Guard in my routing function, I wrapped my component with a HOC function. Something like this

<Route path="/profile" component={withAuth(UserProfileScreen)} />

So I tried to validate authentication in wrapper function for that I need to connect redux with the wrapper function. So I'm trying like this.

function withAuth(ComponentToProtect) {
    return class extends Component {
        constructor() {
            super();
            this.state = {
                loading: true,
                redirect: false,
            };
        }
        async componentDidMount() {
            // logic to check signin
          this.props.manageUserLogin(true)
        }

        render() {
            const { loading, redirect } = this.state;
            if (loading) {
                return null;
            }
            if (redirect) {
                 return <Redirect to="/" />;
            }
            return (
                <React.Fragment>
                    <ComponentToProtect {...this.props} />
                </React.Fragment>
            );
        }
    };
}
const mapStateToProps = (state) => {
    return {
        isUserLoggedIn: state.authR.isUserLoggedIn,\
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        manageUserLogin: (action) =>
            dispatch(
                actionCreators.manageUserLogin(action)
            ),
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(withAuth);`

When I connect redux with wrapper function, I'm getting like TypeError: Object(...) is not a function error.

Upvotes: 1

Views: 291

Answers (1)

Red Baron
Red Baron

Reputation: 7642

try this

const withAuthHoc = compose(connect(mapStateToProps, mapDispatchToProps), withAuth);

export default withAuthHoc;

Upvotes: 1

Related Questions