简体   繁体   中英

How can i persist data in react native application?

I want to create a React Native app that persists local data and then syncs to the server. Please help me to find a way for this.

React Native provides methods to persist data. Some are provided out of the box while others are libraries you have to install and use. Below are popular methods of persisting data in React Native

  • AsyncStorage
  • React Native SQLite 2
  • Realm
  • React Native Local MongoDB

refer https://pusher.com/tutorials/persisting-data-react-native

For persisting data on your platform iOS / Android I would recommend to use AsyncStorage .

Check out the documentation .

AsyncStorage-ReactNative

Then for sync for the server you have to manage your data I guess with your data persisting diagram .

SET DATA

_storeData = async () => {
  try {
    await AsyncStorage.setItem('@MySuperStore:key', 'I like to save it.');
  } catch (error) {
    // Error saving data
  }
};

GET DATA

_retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('TASKS');
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
  } catch (error) {
    // Error retrieving data
  }
};

Then when you set a data to the phone, make a Network call with fetch() api of the React Native , then do your sync job with your backend.

local data and then sync

import {AsyncStorage} from 'react-native';

Persisting data:

_storeData = async () => {
  try {
    await AsyncStorage.setItem('@MySuperStore:key', 'I like to save it.');
  } catch (error) {
    // Error saving data
  }
};

Fetching data:

_retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('TASKS');
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
  } catch (error) {
    // Error retrieving data
  }
};

For persisting data locally use realm. Read the documentation from https://realm.io/blog/introducing-realm-react-native/

Before using Realm, please do check your node version. Currently realm only support node V8 and V10. Like I am currently working on node V11.5, I don't want to downgrade my node.

React Native Local MongoDB is Deprecated , I think there will be no further enhancement and support for this library. Do check https://github.com/antoniopresto/react-native-local-mongodb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM