ReactJs: How to execute code before a component mounts since componentWillMount is deprecated?

711 Views Asked by At

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?

2

There are 2 best solutions below

0
On

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

0
On

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}
            />