Mills
Mills

Reputation: 57

react native if else statement won't run function automatically

trying to run a function on a if else statement in react native, however if I just call it straight up like this.removeAlert() I get an infinite loop crash because of calling setState. I read that you should call it within a function, which works fine in onPress functions, but for me its not working outside of that.

  class Settingscontainer extends Component {
  constructor() {
   super();
   this.removeAlert = this.removeAlert.bind(this);
  }
  removeAlert = () => {
    console.log("please work");
    // this.setState({ successAlert: false });
  };

  render() {
    this.props.isFocused
      ? console.log("Focused") // console.log working
      : () => {                // not working
          this.removeAlert();
        };
    return(<View>code...</View>
    )  
    }}
     

Upvotes: 0

Views: 807

Answers (1)

blaz
blaz

Reputation: 4078

What you do is equivalent to this:

function callRemoveAlert() {
  this.removeAlert();
}
this.props.isFocused
    ? console.log("Focused")
    : callRemoveAlert

You define a function to call this.removeAlert(), but never invoke that function. To make your code work, you need to do:

this.props.isFocused
    ? console.log("Focused")
    : this.removeAlert()

But since in removeAlert, you intend to modify state, so I don't think you should do it this way. By default, React component, with every change in props and state, will invoke render. With your implementation, render will trigger setState, and state change will trigger render, causing an infinite loop of state update and render. A better way to do this is to use componentDidUpdate:

componentDidUpdate(prevProps) {
    if (this.props.isFocused !== prevProps.isFocused) {
      (this.props.isFocused) ?
      ? console.log("Focused")
      : this.removeAlert();
    }
}

render() {
    return(<View>code...</View>
    )  
    }}

Upvotes: 1

Related Questions