官术网_书友最值得收藏!

Using AsyncStorage

When building a React Native app, it's important to understand how mobile devices handle the memory used by each app. Our app will be sharing the memory with the rest of the apps in the device so, eventually, the memory which is using our app will be claimed by a different app. Therefore, we cannot rely on putting data in memory for later use. In case we want to make sure the data is available across users of our app, we need to store that data in the device's persistent storage.

React Native offers an API to handle the communication with the persistent storage in our mobile devices and this API is the same on iOS and Android, so we can write cross-platform code comfortably.

The API is named AsyncStorage, and we can use it after importing from React Native:

import { AsyncStorage } from 'react-native';

We will only use two methods from AsyncStorage: getItem and setItem. For example, we will create within our screen a local function to handle the addition of a product to the full list of products:

/*** AddProduct ***/

...
async addNewProduct(name) {
const newProductsList = this.state.allProducts.concat({
name: name,
id: Math.floor(Math.random() * 100000)
});

await AsyncStorage.setItem(
'@allProducts',
JSON.stringify(newProductsList)
);

this.setState({
allProducts: newProductsList
});
}
...

There are some interesting things to note here:

  • We are using ES7 features such as async and await to handle asynchronous calls instead of promises or callbacks. Understanding ES7 is outside the scope of this book, but it is recommended to learn and understand about the use of async and await, as it's a very powerful feature we will be using extensively throughout this book.
  • Every time we add a product to allProducts, we also call AsyncStorage.setItem to permanently store the product in our device's storage. This action ensures that the products added by the user will be available even when the operating system clears the memory used by our app.
  • We need to pass two parameters to setItem (and also to getItem): a key and a value. Both of them must be strings, so we would need to use JSON.stringify, if we want to store the JSON-formatted data.
主站蜘蛛池模板: 平度市| 砀山县| 左权县| 柯坪县| 那曲县| 托里县| 临洮县| 保德县| 阳城县| 漳州市| 凉山| 彩票| 雅江县| 黄冈市| 赤城县| 礼泉县| 远安县| 当雄县| 崇明县| 临汾市| 城口县| 涞水县| 虞城县| 安西县| 呼玛县| 开原市| 察雅县| 洮南市| 武宁县| 阳东县| 曲水县| 永济市| 锦州市| 东明县| 萨嘎县| 嵊泗县| 武山县| 万年县| 龙游县| 盘锦市| 新河县|