1

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 (        )

}

}
thanks_in_advance
  • 2,603
  • 6
  • 28
  • 44

3 Answers3

4

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
  };
}
namth
  • 2,747
  • 1
  • 9
  • 17
1

You can try to use getDerivedStateFromProps. This will be invoked for the first time and for any subsequent update.

static getDerivedStateFromProps(props, state) {
    if (localStorage.getItem("JWT") && state.logged_out_redirect) {
        return {logged_out_redirect: false};
    }
    return null;
}
0

You can replace it with componenDidMount:

componentDidMount() {   
    if (localStorage.getItem("JWT")) {
        this.setState({logged_out_redirect: false});
    }
}
Ville Venäläinen
  • 2,444
  • 1
  • 15
  • 11
  • Thanks for offering to help. I already tried it. Here's why it doesn't work. The render method contains `if (this.state.logged_out_redirect) { return () }`. By the time it mounts, it's already re-directed to another component. So `componentDidMount` either doesn't fire or fires too late. – thanks_in_advance Apr 06 '19 at 04:29