2

What's the best way to make an offline friendly app where my requirement is to never stop the user from submitting data regardless of internet connectivity.

When connectivity is there POST data directly to the online server and when there's no connection then store data in some kind of local storage(reliable) until the connection is established again in which case send data immediately to the online server.

1 Answer 1

4

You can use this library, i've used in multiple projects of mine

react-native-netinfo will return you a callback when app is not connected with internet

you can perform and handle further action there *

A small example
now you'll get the value in redux if your device is connected or not

*

and remember it doesn't work well in simulator test on real device

import React from 'react';
// import NetInfo from "@react-native-community/netinfo";
import { View, Text, Dimensions, StyleSheet ,NetInfo} from 'react-native';
import {toggleNetworkState} from '../../actions/list';
import { connect } from 'react-redux';
const { width } = Dimensions.get('window');

function MiniOfflineSign() {
  return (
    <View style={styles.offlineContainer}>
      <Text style={styles.offlineText}>No Internet Connection</Text>
    </View>
  );
}

class OfflineNotice extends React.Component {
  state = {
    isConnected: false
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    // NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => {
    this.setState({
        isConnected: isConnected
    })
    this.props.toggleNetworkState(isConnected);
  };

  

  render() {
    if (!this.props.state.list.isNetwork) {
      return <MiniOfflineSign />;
    }
    return null;
  }
}

const styles = StyleSheet.create({
  offlineContainer: {
    backgroundColor: '#b52424',
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    width,
    position: 'absolute',
    top: 64,
    zIndex:1,
  },
  offlineText: { color: '#fff' }
});


const mapStateToProps = state => ({
    state
    });

export default connect(mapStateToProps, {toggleNetworkState})(OfflineNotice);

Sign up to request clarification or add additional context in comments.

2 Comments

Sure I will try that. Do you have any implementation of the above scenario in a public git??
Thanks a ton! I will try this for sure in my app. I will reply here if i get stuck somewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.