Reputation: 3
my app need to internet for fetch database. when WIFI is on and open app everything is good and after show logo for some second navigate to main page, but when my WIFI is off and open app undoubted can't fetch data but when turn on my WIFI data not fetching, it mean the state that save data not update with connect to internet, should close app open again for fetching...
import React, {Component} from 'react';
import {StyleSheet, View, Animated, StatusBar} from 'react-native';
import { Spinner } from 'native-base';
import Network from './Network'
const SuperUrl = 'http://site.domain'
export default class Intro extends Component {
constructor(){
super();
this.state={
isLoading: true,
dataSource: null,
}
}
componentDidMount()
{
return fetch(SuperUrl+'/check')
.then((response)=> response.json())
.then((responseJson)=>this.setState({
isLoading:false,
dataSource: responseJson.app_update
}));
}
render() {
var appStatus = this.state.dataSource;
if(this.state.isLoading===false && appStatus===0)
{
setTimeout(() => {
this.props.navigation.replace('test')
}, 2500);
}
return (
<View>...Logo Content...</View>
<Network />
)
}
}
and my component that check internet connect is :
import React, { Component } from 'react'
import { NetInfo, View } from 'react-native'
import {Root, Toast} from 'native-base'
export default class Network extends Component {
constructor(){
super();
this.state={connection: null}
}
componentWillMount(){
NetInfo.isConnected.addEventListener('connectionChange',this.handleconnectionChange);
}
componentWillUnmount(){
NetInfo.isConnected.removeEventListener('connectionChange',this.handleconnectionChange);
}
handleconnectionChange= (isConnected) => {this.setState({connection:isConnected})}
render() {
return (
<View style={{flex:1,}}>
<Root>
{(this.state.connection!=null && this.state.connection==false)?
Toast.show({
text: "at first please connect to internet.",
duration: 0,
type: 'danger'
})
:
null
}
</Root>
<Root>
{(this.state.connection!=null && this.state.connection==true)?
Toast.hide()
:
null
}
</Root>
</View>
)
} }
Upvotes: 0
Views: 566
Reputation: 570
First , Install this npm package [https://www.npmjs.com/package/react-native-offline][1] It will provide two components, 1) NetworkProvider 2) NetworkConsumer
Then , Wrap your entire app inside NetworkProvider as follows
<NetworkProvider>
<App />
</NetworkProvider>
And Finally , You can wrap the child component inside the NetworkConsumer as follows,
<NetworkConsumer>
{({ isConnected }) => (
isConnected ? (
<Button title="Download image" onPress={downloadImage} />
) : (
<Text>Downloading images is disabled since you are offline</Text>
)
)}
</NetworkConsumer>
Hope this works... ;-)
Upvotes: 1