반응형
Leo's Story
[React Native] Async Storage - 로컬저장소 사용 본문
반응형
Asycn Storage 는 String 데이터만 저장할 수 있음.
JSON의 경우 JSON.stringfy()를 통해 직렬화를 하고 JSON.parse()를 통해 로드.
1. npm install
npm install @react-native-async-storage/async-storage
2. 프로젝트 상단 Import
import AsyncStorage from '@react-native-async-storage/async-storage';
3. 저장
-> key: value 형태로 저장
String
const storeData = async (value) => {
try {
await AsyncStorage.setItem('@storage_Key', value)
} catch (e) {
// 저장 에러 발생시
}
}
Object
const storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value)
await AsyncStorage.setItem('@storage_Key', jsonValue)
} catch (e) {
// 저장 에러 발생시
}
}
4. 읽기
Key 값을 통해 value 가져오기
String
const getData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key')
if(value !== null) {
// value가 존재할 때 동작
}
} catch(e) {
// 에러 발생 시
}
}
Object
const getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('@storage_Key')
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch(e) {
// 에러 발생 시
}
}
@참고자료
https://react-native-async-storage.github.io/async-storage/docs/usage/
반응형
'개발 > React Native' 카테고리의 다른 글
[React Native] React Native Navigation (0) | 2022.08.17 |
---|---|
[React Native] React vs React Native(RN) (0) | 2022.08.03 |
Comments