개발 공부/React Native
[React Native] AsyncStorage 사용법
MOON달
2022. 12. 30. 19:17
728x90
반응형
AsyncStorage란?
- 암호화되지 않은 비동기적인 데이터를 관리하는 Key-Value 시스템
- 앱 전역에서 사용 가능하며 LocalStorage 대신에 사용해야 한다
- 앱이 다운되더라도 기존 저장된 변수 및 세팅 사항들이 보존된다
- 키-값 형태로 보관됨에 있어 저장되는 값은 무조건 문자열로 취급되어야한다
- 저장할때 JSON.stringfy() 사용
- 가져올때 JSON.parse() 사용
- 비동기 처리를 위하여 async/await과 에러 핸들링을 위해 try-catch 문을 써준다.
- key 값이 공백 또는 null 일 때에는 error를 throw 해주고, value 가 존재하지 않는다면 null을 반환하도록 한다.
Install
npm install @react-native-async-storage/async-storage
자세한 document는 깃허브에서 찾아볼 수 있다.
https://github.com/react-native-async-storage/async-storage
GitHub - react-native-async-storage/async-storage: An asynchronous, persistent, key-value storage system for React Native.
An asynchronous, persistent, key-value storage system for React Native. - GitHub - react-native-async-storage/async-storage: An asynchronous, persistent, key-value storage system for React Native.
github.com
import 하기
import AsyncStorage from 'https://github.com/react-native-async-storage/async-storage'
Storage에서 데이터 꺼내오기
async await 사용 (비동기 처리)
예시 (투두리스트)
import AsyncStorage from "@react-native-async-storage/async-storage";
...
useEffect(() => {
// 현재의 최신 todos를 AsyncStorage에 저장
const saveTodos = async () => {
await AsyncStorage.setItem("todos", JSON.stringify(todos));
};
if (todos.length > 0) saveTodos();
}, [todos]);
useEffect(() => {
const getData = async () => {
const resp_todos = await AsyncStorage.getItem("todos"); // todos 배열
const resp_tag = await AsyncStorage.getItem("tag"); // undefiend / null
setTodos(JSON.parse(resp_todos));
setTagTodo(resp_tag ?? "js");
};
getData();
}, []);
...
728x90