So I have an app with an activity. The app checks for Internet connection at the beginning. If there are no Internet connection, it will show a screen with a button to refre
You can force update the component. Check this: https://reactjs.org/docs/react-component.html#forceupdate
It will re-render the component.
check this example:
class App extends Component{
constructor(){
super();
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
};
forceUpdateHandler(){
this.forceUpdate();
};
render(){
return(
<div>
<button onClick= {this.forceUpdateHandler} >FORCE UPDATE</button>
<h4>Random Number : { Math.random() }</h4>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
class MyScreen extends Component {
constructor(props) {
super(props)
this.state = {
lastRefresh: Date(Date.now()).toString(),
}
this.refreshScreen = this.refreshScreen.bind(this)
}
refreshScreen() {
this.setState({ lastRefresh: Date(Date.now()).toString() })
}
render() {
return (
<View>
<Text>My Screen</Text>
<Text>Last Refresh: {this.state.lastRefresh}</Text>
<Button onPress={this.refreshScreen} title="Refresh Screen" />
</View>
)
}
}
// also put in main View Date(Date.now())
I would suggest putting your API call in it's own function fetchData within your component. fetchData can also setState after a successful fetch which will cause a re-render and show the fresh data. If you want to fetch fresh data on componentDidMount and also on a button click, then create a fetchData function and call that from within componentDidMount, then for your button just set your onPress prop appropriately onPress={this.fetchData}
Remember by calling setState function on your component, you can refresh it. if there's a button that's going to refresh the page, i would do this:
<Button onPress={() => this.setState({dummy: 1})} />
calling setState will update your component no matter what you object you pass to it. I'm not sure if re-rendering page, calls componentDidMount function, so maybe you need to move your API calls to some funciton func and call this function in your componentDidMount, and also after each button press event. example:
componentDidMount() {
apiCalls()
}
apiCalls() {
.... // your code
this.setState({dummy: 1})
}
render() {
<View>
...
<Button onPress={this.apiCalls.bind(this)} />
...
</View>
}