react-native에서 젤 편하고 쉽게 쓸 수 있는 db다.
(네이티브로 빌드되면서 sqlite가 되는 것 같음)
RN 공식문서
- https://reactnative.dev/docs/asyncstorage.html
⇒ Deprecated. 향후에 없어질 거니,
@react-native-community/async-storage
를 써라.참고자료
- https://morioh.com/p/4ec2444d10da (여러 무료강의들 많음)
@react-native-community/async-storage
설치 (RN ≥ 0.60 기준)
#패키지 설치 $ yarn add @react-native-community/async-storage #링킹 $ npx pod-install
사용
//임포트 import AsyncStorage from '@react-native-community/async-storage';
사용하기에 앞서,
Async Storage
는 문자열 데이터만 저장할 수 있는 것을 알아야함.따라서
객체
를 저장하려면 먼저 serialize 해서 저장하고, 데이터를 가져올 땐 이걸 풀어서 쓰면 됨.JSON.stringify()
← object 저장 시 serialize
JSON.parse()
← object 값 불러올 시 deserialize
문자열 저장 및 가져오기
//문자열 저장 export const storeData = async (key, value) => { try { console.log("AsyncStorage 문자열 저장 인자 검사. key : ", key," value : ", value); await AsyncStorage.setItem(key, value) } catch (e) { console.log("AsyncStorage 문자열 저장 오류"); } console.log("AsyncStorage 문자열 저장 완료"); } //문자열 읽기 export const getData = async (key) => { try { console.log("AsyncStorage 문자열 읽기 인자 검사. key : ", key); return await AsyncStorage.getItem(key) } catch (e) { console.log("AsyncStorage 문자열 불러오기 오류"); } console.log("AsyncStorage 문자열 불러오기 완료"); }
객체 저장 및 가져오기
//객체 저장 export const storeObjData = async (key, value) => { try { console.log("AsyncStorage 오브젝트 저장 인자 검사. key : ", key," value : ", value); const jsonValue = JSON.stringify(value) await AsyncStorage.setItem(key, jsonValue) } catch (e) { console.log("AsyncStorage 오브젝트 저장 오류"); } console.log("AsyncStorage 오브젝트 저장 완료"); } //객체 읽기 export const getObjData = async (key) => { try { console.log("AsyncStorage 오브젝트 읽기 인자 검사. key : ", key); const jsonValue = await AsyncStorage.getItem(key) return jsonValue != null ? JSON.parse(jsonValue) : null; } catch (e) { console.log("AsyncStorage 오브젝트 불러오기 오류"); } console.log('AsyncStorage 오브젝트 불러오기 완료') }
삭제하기
//삭제하기 export const removeValue = async (key) => { try { await AsyncStorage.removeItem(key) } catch(e) { console.log("AsyncStorage 삭제 오류"); } console.log('AsyncStorage 삭제 완료') }