How do I Print an Exception in Python?
April 29, 2024
Home >> React Native Q&A >> setTimeout in React Native
Here you can see a code that crashes the app and shows the error that this. setState is not a function.
class CowtanApp extends Component {
constructor(props){
super(props);
this.state = {
timePassed: false
};
}
render() {
setTimeout(function(){this.setState({timePassed: true})}, 1000);
if (!this.state.timePassed){
return <LoadingPage/>;
}else{
return (
<NavigatorIOS
style = {styles.container}
initialRoute = {{
component: LoginPage,
title: 'Sign In',
}}/>
);
}
}
}
You see this is a keyword that developers can’t use inside a callback method of setTimeout. JavaScript’s keyword does not directly refer to the component’s instance when a regular function is used as a callback method by using the setTimeout function. It shows that a function can be anything: a window, a button, or any object. This problem happens because the setState function is not available to be used globally.
Now, you can see that developers can follow these two approaches to overcome this issue.
You see the bind keyword needs to be binded inside the function of this specific class and an example is given below.
class CowtanApp extends Component {
constructor(props) {
super(props);
this.state = {
timePassed: false
};
this.handleTimeout = this.handleTimeout.bind(this);
}
componentDidMount() {
setTimeout(this.handleTimeout, 1000);
}
handleTimeout() {
this.setState({ timePassed: true });
}
render() {
if (!this.state.timePassed) {
return <LoadingPage />;
} else {
return (
<NavigatorIOS
style={styles.container}
initialRoute={{
component: LoginPage,
title: 'Sign In',
}}
/>
);
}
}
}
In this, you just have to implement arrow functions according to the standards of ES6+ to resolve all your requirements. However, the arrow functions do not have this keyword bound to them. That’s why the arrow function is always represented by the keyword “this” in arrow functions and the example is given below.
class CowtanApp extends Component {
constructor(props) {
super(props);
this.state = {
timePassed: false
};
}
componentDidMount() {
setTimeout(() => {
this.setState({ timePassed: true });
}, 1000);
}
render() {
if (!this.state.timePassed) {
return <LoadingPage />;
} else {
return (
<NavigatorIOS
style={styles.container}
initialRoute={{
component: LoginPage,
title: 'Sign In',
}}
/>
);
}
}
}
Digital Valley, 423, Apple Square, beside Lajamni Chowk, Mota Varachha, Surat, Gujarat 394101
D-401, titanium city center, 100 feet anand nagar road, Ahmedabad-380015
+91 9913 808 2851133 Sampley Ln Leander, Texas, 78641
52 Godalming Avenue, wallington, London - SM6 8NW