Constructor getting called twice React Component Constructor getting called twice React Component reactjs reactjs

Constructor getting called twice React Component


First of all, you should not call Redux actions or any kind of AJAX from within the constructor. Those things should be done in componentDidMount().

Second, I would request the language from the store as part of props. If not defined, then in componentDidMount() call your setDefaultLanguage().

I would do at least the following:

export class LoginPage extends React.Component {  componentDidMount() {    if (!this.props.lang) {        this.setDefaultLanguage();    }  }  changeLanguage = (e) => {    const lan = e.target.value;    this.props.setLanguage(lan);  };  setDefaultLanguage = () => {    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';    if(defaultLanguage == 'es'){      this.props.setLanguage(defaultLanguage);    }else{      this.props.setLanguage('en');    }  }  render() {    return(      <div className="box-layout">        <div className="box-layout__box">          <h1 className="box-layout__title">Expensify</h1>          <p>It\'s time to get your expenses under control.</p>          <button className="button" onClick={this.props.startLogin}>Log in with google</button>          <select className="select" onChange={this.changeLanguage}>            <option value="en">English</option>            <option value="es">Español</option>          </select>        </div>      </div>    )  };}const mapStateToProps = state => ({    // Assuming `steate.lang` is where you would set the language.    lang: state.lang});const mapDispatchToProps = (dispatch) => ({  startLogin: () => dispatch(startLogin()),  setLanguage: (language) => dispatch(setLanguage(language))});const mergeProps = (stateProps, dispatchProps) => ({ ...stateProps, ...dispatchProps });export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(LoginPage);


I was having the same issue because I was redirecting the user inside my public routes. So it was rendering the component twice. In case you are using

history.push('/');

This is going to render the component twice.