별개 DB를 사용하지않고 로컬 핸드폰 데이터로 저장해야할때 사용하는 라이브러리이다.
설치 방법 :
npm i @react-native-async-storage/async-storage
설치가 완료됐다면 다음과같이 import를 해주자,
import AsyncStorage from '@react-native-async-storage/async-storage';
이제 설치와 import는 끝났다.
다음과같이 사용하면된다.
우선 목표는 당연히, save 와 load기능이다.
우선적으로 save자체를 해보자,
const saveToDos = async (toSave: any) => {
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
};
엄청 단순하다.
저장하는방식은 다음과같이 async 로 시작해주고 AsyncStorage 여는 부분에서 await으로 저장이 완료될때까지 기다리자.
참고로 STORAGE_KEY는 자기가 하고싶은 단어로 하면된다. (왠만해선 다른것도 사용할 수 있으니 안겹치는게 좋다.
그럼 load는 어떻게 할까?
const loadToDos = async (): Promise<TodoStorage | null> => {
try {
const s = await AsyncStorage.getItem(STORAGE_KEY);
if (!s) return null;
setToDos(JSON.parse(s));
return JSON.parse(s) as TodoStorage;
} catch (e) {
console.error(e);
return null;
}
};
보통 권장사항으로 로드할때도, 세이브할때도 try catch를 넣어주는게 맞다.
ex) 저장공간이 꽉찼다던지, 그런 버그가 발생하면 어떤 에러가 날지 모르니까.
지금같은경우에는 불러올때 만약없다면 catch부분으로 빠지거나, return 자체를 null로 하게 될것이다.
try / catch를 생활화하자.
++ 공식문서 링크 걸어두겠다.
https://reactnative.dev/docs/asyncstorage