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

  • React Native Blueprints
  • Emilio Rodriguez Martinez
  • 372字
  • 2021-07-02 15:19:59

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.
主站蜘蛛池模板: 新竹县| 莱阳市| 辉县市| 明水县| 内丘县| 黄平县| 威海市| 杭锦后旗| 隆化县| 万山特区| 鄱阳县| 遵化市| 嘉荫县| 博白县| 阜城县| 龙陵县| 和顺县| 梁平县| 渝北区| 津南区| 永康市| 江永县| 酉阳| 厦门市| 湘乡市| 龙里县| 长寿区| 宁德市| 临颍县| 钟山县| 周口市| 逊克县| 贡嘎县| 定远县| 开鲁县| 额尔古纳市| 上栗县| 凉山| 三穗县| 梧州市| 柘荣县|