앱을 종료 후 다시 실행하였을 때, 데이터가 남아있지 않는 문제가 있을 수 있다.
이때, 브라우저의 localStorage처럼 key-value기반으로 로컬에 데이터를 저장할 수 있게 해주는 라이브러리를 사용한다.
@react-native-async-storage/async-storage
localstorage와 마찬가지로, 문자열 데이터만 사용이 가능하다.
따라서 JSON.stringify 메서드와 JSON.parse 메서드의 사용이 필요하다.
하지만 AsyncStorage는 localstorage와는 다르게 비동기 처리가 필요하다.
- 다음과 같이 사용할 수 있다.
import React, { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { ScrollView, TextInput, StyleSheet, Text } from "react-native";
import Item from "./Item";
const List = () => {
const [textData, setTextData] = useState("");
const [listData, setListData] = useState([]);
const handleSubmit = async () => {
const newList = [{title: textData, content: textData},
...listData];
await AsyncStorage.setItem("textData", JSON.stringify(newList));
setListData(newList);
setTextData("");
alert("등록");
}
useEffect(() => {
const getData = async () => {
const storageData =
JSON.parse(await AsyncStorage.getItem("textData"));
if(storageData) {
console.log("GET data from storage");
setListData(storageData);
}
}
// AsyncStorage에 저장된 데이터가 있다면, 불러온다.
getData();
}, []);
return (
<ScrollView>
{listData.length > 0 ?
listData.map((el, idx) =>
<Item
key={idx}
title={el.title}
content={el.content}
/>)
: <Text>데이터가 없습니다.</Text>}
<TextInput
style={styles.TextInputStyle}
placeholder="title"
defaultvalue={textData}
value={textData}
onChangeText={(text) => setTextData(text)}
onSubmitEditing={handleSubmit}
/>
</ScrollView>
);
}
const styles = StyleSheet.create({
TextInputStyle: {
fontSize: 20,
padding: 15,
margin: 10,
borderWidth: 1,
}
});
export default List;
보안을 더 중요시한다면, EncryptedStorage를 사용할 수 있다.
사용법은 거의 동일하기에, 보안이 필요한 데이터를 저장할 상황이라면, EncryptedStorage를 사용한다.
- AsyncStorage 깃허브 : https://react-native-async-storage.github.io/async-storage/
Async Storage | Async Storage
Homepage for React Native Async Storage project
react-native-async-storage.github.io
- EncryptedStorage 깃허브 : https://github.com/emeraldsanto/react-native-encrypted-storage#readme
GitHub - emeraldsanto/react-native-encrypted-storage: React Native wrapper around EncryptedSharedPreferences and Keychain to pro
React Native wrapper around EncryptedSharedPreferences and Keychain to provide a secure alternative to Async Storage. - GitHub - emeraldsanto/react-native-encrypted-storage: React Native wrapper ar...
github.com