Search code examples
reactjsreact-lifecycle

alternative for this componentWillMount case?


I'm trying to refactor some old code.

componentWillMount has been deprecated.

How would I refactor it here into something else?

class Detail extends React.Component{

constructor(props) {
    super(props);

    this.state = {
        logged_out_redirect: true
    };
}   

componentWillMount() {  //<------ this lifecycle method has been deprecated, how do I replace it?

    if (localStorage.getItem("JWT")) {
        this.setState({logged_out_redirect: false});
    }
}

render() {

    if (this.state.logged_out_redirect) {
        return (<Redirect to={"/login"}/>)
    }

    return (        )

}

}

Solution

  • In this case(depend on case what you're trying to do in componentWillMount). You cant put it inside your constructor()

    constructor(props) {
      super(props);
    
      this.state = {
        logged_out_redirect: localStorage.getItem("JWT") ? false : true
      };
    }