1

As the official docs say componentWillMount is deprecated now and is recommended to put any code that is meant for this lifecycle method into the constructor.

Honestly I don't know how to do that. I've got this code that was meant for componentWillMount but how I'm supposed to implement it into the constructor:

if (window.localStorage.getItem("authToken"))
  this.setState({ isAuthenticated: true });

I had it like this:

constructor() {
  super();
  this.state = {
    users: [],
    username: "",
    email: "",
    title: "something",
    isAuthenticated: false
  };
  if (window.localStorage.getItem("authToken"))
    this.setState({ isAuthenticated: true });
}

but the condition wasn't triggered when it was supposed to trigger. How are conditional statements supposed to work in a constructor ?

Any guidance much appreciated.

Edit:

constructor() {
  super();
  this.state = {
    users: [],
    username: "",
    email: "",
    title: "something",
    isAuthenticated: window.localStorage.getItem("authToken") ? true : false
  };
}

I'll try this as this does make sense to me.

norbitrial
  • 14,716
  • 7
  • 32
  • 59
mr_incredible
  • 837
  • 2
  • 8
  • 21
  • 1
    Have you considered putting it into componentDidMount()? – boosted_duck Feb 25 '20 at 06:21
  • I've thought about it but if that would be a good idea it would've been mentioned in the docs. – mr_incredible Feb 25 '20 at 06:22
  • I think setting the state in your constructor is not a good idea, https://stackoverflow.com/questions/34961853/what-will-happen-if-i-use-setstate-function-in-constructor-of-a-class-in-react – boosted_duck Feb 25 '20 at 06:31
  • Thing to note don't store your auth token in localstorage you are exposing it to XSS attacks – TZiebura Feb 25 '20 at 06:49
  • please check this https://stackoverflow.com/questions/52092341/how-should-i-alternate-componentwillmount?noredirect=1 – bajran Feb 25 '20 at 07:08

1 Answers1

0

You can't expect the exact flow of componentWillMount, and requires you to think in a slightly different way.

You can do this.


componentDidMount() {
  if (window.localStorage.getItem("authToken"))
    this.setState({ isAuthenticated: true });
}


render() {
  // Since this function will be called before
  // componentDidMount, handle the false case here

  if (!this.state.isAuthenticated) {
    return null; // or any fallback UI for unAuthenticated user 
  }

  return (
   // the original UI
  )
}


Pushkin
  • 3,336
  • 1
  • 17
  • 30