Last active
June 3, 2019 07:46
-
-
Save ritikrishu/1a866e4f720408e057273df387762b44 to your computer and use it in GitHub Desktop.
React native offline screen wrapper example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function connectionAwareActivity(WrappedComponent) { | |
return class extends PureComponent { | |
constructor(props) { | |
super(props); | |
this.state = { isConnected: false }; | |
this.switchConnectivity = this.switchConnectivity.bind(this); | |
} | |
static navigationOptions = WrappedComponent.navigationOptions | |
componentDidMount() { | |
NetInfo.addEventListener('connectionChange', this.switchConnectivity); | |
NetInfo.isConnected.fetch().then(isConnected => { | |
this.setState({ isConnected }); | |
}); | |
} | |
componentWillUnmount(){ | |
NetInfo.removeEventListener('connectionChange', this.switchConnectivity); | |
} | |
switchConnectivity(type) { | |
if(type === 'none'){ | |
this.setState({isConnected: false}) | |
} | |
else{ | |
this.setState({isConnected: true}) | |
} | |
} | |
render() { | |
return this.state.isConnected ? ( | |
<WrappedComponent {...this.props} /> | |
) : ( | |
<OfflineScreen/> | |
); | |
} | |
}; | |
} |
@tejashwikalptaru yes it is, should use getConnectionInfo
instead, but both API's return promise or take callback, this is just example code to represent the problem.
I've already tried componentWillMount
but placing console.log('render was called')
in render function still logs twice on screen navigation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you tried replacing
componentDidMount
withcomponentWillMount
?According to lifecycle docs, the
componentDidMount
runs after the first render, and hence after the first render incomponentDidMount
you are changing the state, which will result in second render call.musefind
gitbooks
react component
You should also handle "unknown" case with "none" and by the way
fetch()
is deprecated:React native docs