0

I am trying to redirect user to home page conditionally before component mounts:

 componentWillMount(){
    console.log("componentWillMount is called.")
    let userHasNotChosenOpportunity = true
    if (userHasNotChosenOpportunity) {
      this.props.history.push("/home")
    }
  }

I have two problems:

  1. componentWillMount never gets called
  2. componentWillMount is deprecated and there seems to be no alternative to execute code before component mounts.

Any suggestions?

AG_HIHI
  • 1,705
  • 5
  • 27
  • 69
  • Did you try calling the redirect inside constructor(props) {} – Sinan Yaman Dec 07 '20 at 12:55
  • is it a problem for you to use componentDidMount? – VersifiXion Dec 07 '20 at 12:57
  • 1
    Does this answer your question? [How should I alternate componentWillMount()?](https://stackoverflow.com/questions/52092341/how-should-i-alternate-componentwillmount) – Jax-p Dec 07 '20 at 12:57
  • @SinanYaman the problem with that is render gets executed – AG_HIHI Dec 07 '20 at 13:00
  • @MarcCharpentier with componentDidMount render gets executed – AG_HIHI Dec 07 '20 at 13:00
  • I think this is tribble idea if u redirect user into component using this functions , u should probably use route redirect or something like this for doing this! – b3hr4d Dec 07 '20 at 13:01
  • @Jax-p the problem with componentDidMount and constructor is that render gets executed before redirecting – AG_HIHI Dec 07 '20 at 13:01
  • @b3hr4d how do I perform the condition check before component gets rendered – AG_HIHI Dec 07 '20 at 13:04
  • @AhmedGhrib There are more answers... The constructor is certainly called before rendering. Also getDerivedStateFromProps() is next method called after constructor - right before render(). See the whole [React life cycle](https://i2.wp.com/programmingwithmosh.com/wp-content/uploads/2018/10/Screen-Shot-2018-10-31-at-1.44.28-PM.png?ssl=1). – Jax-p Dec 07 '20 at 13:04
  • should make protected root for checking props like this answer : https://stackoverflow.com/a/65178365/12608714 – b3hr4d Dec 07 '20 at 13:06
  • @Jax-p True, but the code inside render still gets executed. I need to redirect and to prevent the code inside render to be executed. – AG_HIHI Dec 07 '20 at 13:07

2 Answers2

0

You should try calling it on componentDidMount or if you for some reason really need to use componentWillMount you can use UNSAFE_componentWillMount but as indicated it is unsafe

Runner
  • 81
  • 8
0

I solved it like this:

import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const OpportunityRedirectRoute = ({
  component: Component,
  opportunities,
  ...rest
}) => {
  let userHasNotChosenOpportunity =
    Object.keys(opportunities.chosen_opportunity).length === 0 &&
    opportunities.chosen_opportunity.constructor === Object;

  return (
    <Route
      {...rest}
      render={(props) =>
        userHasNotChosenOpportunity ? (
          <Redirect to="/courses" />
        ) : (
          <Component {...props} />
        )
      }
    />
  );
};

OpportunityRedirectRoute.propTypes = {
  opportunities: PropTypes.object.isRequired,
};

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

export default connect(mapStateToProps)(OpportunityRedirectRoute);

In App.js:

 <OpportunityRedirectRoute
              exact
              path="/opportunity"
              component={OpportunityPage}
            />
AG_HIHI
  • 1,705
  • 5
  • 27
  • 69