3

I am trying to create a loading screen in React Native that will navigate to a confirmation screen once the time from a setTimeout function has been fulfilled. Currently, the screen loads, but does not navigate to the confirmation screen after the setTimeout interval.

import React from 'react';
import { Text, View, Image } from 'react-native';
import { Actions as NavigationActions } from 'react-native-router-
flux';

import styles from './styles';

export default class ProcessingLoader extends React.Component {
  constructor(props) {
   super(props);
   this.state = {};
 }



componentDidMount() {
    setTimeout(this.navigateToConfirmation, 3000);
   }



navigateToConfirmation() {
    NavigationActions.checkoutConfirmation({ product: this.props.product, type: 'reset' });
  }



renderLoader() {
    return (
      <View style={styles.textContainer}>
        <Text style={styles.loaderText}>Processing Order ...</Text>
      </View>
    );
  }



 render() {

    return (
      <View style={{ flex: 1 }}>
        {this.renderLoader()}
      </View>
    );
  }
}

I've tried using setTimeout in componentDidMount as well as in render. I've also tried using and arrow function vs not using an arrow function. Am I utilizing setTimeout completely wrong here? I'm afraid that I don't understand why it will not navigate to the next screen after 3 seconds. Thanks in advance!

Gabi Procell
  • 72
  • 2
  • 9
  • 2
    Should always be careful with the `this` keyword in javascript... contexts are [weird](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work), see [the this problem](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#The_this_problem) in the `setTimeout()` MDN (note the section covers @Chris' answer below) – Patrick Barr Jul 06 '17 at 20:13
  • thanks for the post dude, i was actually looking for an answer to why my navigation wasn't working inside the componentdidmount(), just realize i had to create a function, and call the navigation from there – Nicolas Silva Aug 01 '19 at 22:13

1 Answers1

3

You are not invoking the function, use parenthesis to do that. Also, the first parameter is a callback, so put your invokation inside a function, like this:

componentDidMount() {
  setTimeout(function(t){t.navigateToConfirmation()}, 3000, this);
}

or in an arrow function:

componentDidMount() {
  setTimeout(() => {this.navigateToConfirmation()}, 3000);
}
Chris
  • 57,622
  • 19
  • 111
  • 137