Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native reload page

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 refresh the page. The problem is that my API calls (Axios) is located on componentDidMount() where it's called only once after the first render. Is there any way I can reload the page so it calls componentDidMount again?

I mean like total refresh. I am using EXPO btw. Any help is appreciated. Sorry there are no examples, I just wanted to get the idea if possible

like image 699
Kevin Gozali Avatar asked Nov 18 '17 17:11

Kevin Gozali


2 Answers

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()) 
like image 50
Shivo'ham 0 Avatar answered Nov 25 '22 15:11

Shivo'ham 0


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}

like image 40
Nunchucks Avatar answered Nov 25 '22 16:11

Nunchucks