Elessar
Elessar

Reputation: 93

What's wrong with setInterval method?

I'm designing a screen in a mobile app that is supposed to disappear automatically and navigate to the next screen. for that purpose I'm using setInterval in following code :

componentDidMount(){
      Animated.timing(this.state.AnimVal, {
          toValue: 1,
          duration: 500 ,
          delay: 1000,
          useNativeDriver: true,
      }).start();

      var timer = setInterval( () => {
        this.setState({
          isLoaded: true,
        });
      }, 1000);
      if(this.state.isLoaded){
        this.props.navigation.navigate({ routeName: 'Guideline'})
      };
  };

the isLoaded state variable method is supposed to become true and as a result of it, the screen must disappear. but it does not happen and the screen remains. any idea what's wrong with it?

Upvotes: 1

Views: 252

Answers (2)

Lenoarod
Lenoarod

Reputation: 3610

this is because when the setInterval setState called, it will re-render the component, but they don not called componentDidMout. enter image description here

for react-native > 0.6:

static getDerivedStateFromProps(props, state){
if(state.isLoaded){
        //here may be has problem
        props.navigation.navigate({ routeName: 'Guideline'})
   };
}

for react-native < 0.6:

componentWillReceiveProps(nextprops){
if(this.state.isLoaded){
        this.props.navigation.navigate({ routeName: 'Guideline'})
      };
}

I suggest it use componentDidUpdate for your condition. because getDerivedStateFromProps is static. it can not call this.props.navigation

componentDidUpdate(prevProps, prevState, snapshot) {
   if(this.state.isLoaded){
        this.props.navigation.navigate({ routeName: 'Guideline'})
      };
  }

Upvotes: 2

Gaurav Roy
Gaurav Roy

Reputation: 12195

The problem is , you are calling the

if(this.state.isLoaded){
        this.props.navigation.navigate({ routeName: 'Guideline'})
      };

inside the componentDIdMount, so its always false, and even though setState re-renders it and makes the state of isLoadedTrue, but it doesnt call the componentDidMount as per the lifecyle methods of react.SO that condition never gets called again.

You can try to write that particular code inside componentDidUpdate() .

componentDidUpdate(){
if(this.state.isLoaded){
            this.props.navigation.navigate({ routeName: 'Guideline'})
          };
}

And one more thing, rather than setInterval try using setTimeout , coz that will suffice in your case. and use the setTimeout inside the componentDidMount itself. That logic of yours is fine, just the navigation logic put it into comopnentDidUpdate()

Upvotes: 1

Related Questions