Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove event Listener so it would not try to update state when component is unmounted?

I have set some dynamic styles and everything works just fine except when component is unmounted. Then it throws an error: Can't call setState (or forceUpdate) on an unmounted component.

It is the second screen in stack navigator, when I go to third, everything is fine, but when i go to first and component is unmounted it throws an error.

I have tried to remove event listener in componentWillUnmount but unsuccessfully, apparently I am doing something wrong.

Also, I have tried with this approach this.props.navigation.isFocused() and again it works just fine, but then if I am on the third screen and rotate the device and go back, Dimensions event listener do not see change and styling is a mess.

So how can I stop event listener when component is unmounted?

Thanks in advance.

constructor(props) {
    super(props);
    Dimensions.addEventListener("change", dims => {
      // this.props.navigation.isFocused() ?
      this.setState({
        resStyles: {
          imageFlex: Dimensions.get("window").height > 500 ? "column" : "row",
          imageHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
          infoHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
          infoWidth: Dimensions.get("window").height > 500 ? "100%" : "50%"
        }
      });
      // : null;
    });
  }

componentWillUnmount

componentWillUnmount() {
    console.log("Unmounted");

    Dimensions.removeEventListener("change", dims => {
      // this.props.navigation.isFocused() ?
      this.setState({
        resStyles: {
          imageFlex: Dimensions.get("window").height > 500 ? "column" : "row",
          imageHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
          infoHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
          infoWidth: Dimensions.get("window").height > 500 ? "100%" : "50%"
        }
      });
      // : null;
    });
  }
like image 359
FatBoyGebajzla Avatar asked Jan 01 '23 18:01

FatBoyGebajzla


1 Answers

you should make a named function (Methode to be precise) like this

fun_name(){
      // this.props.navigation.isFocused() ?
  this.setState({
    resStyles: {
      imageFlex: Dimensions.get("window").height > 500 ? "column" : "row",
      imageHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
      infoHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
      infoWidth: Dimensions.get("window").height > 500 ? "100%" : "50%"
    }
  });
  // : null;
}

constructor(props) {
    super(props);
    Dimensions.addEventListener("change", this.fun_name);
  }

componentWillUnmount() {
    console.log("Unmounted");

    Dimensions.removeEventListener("change", this.fun_name);
  }

PS: don't forget to bind the function

like image 196
evgeni fotia Avatar answered Jan 05 '23 17:01

evgeni fotia