-> 앱에서의 LocalStorage로 이해하면 된다.
새로고침을 하면 Todo가 다 달라간다.
새로고침해도 유지가 되려면, Component가 mount했을 때 state 값들을 기억해야하는데,
웹에서는 localStorage를 사용한다.
앱에서는 AsyncStorage를 사용한다.
async로 정의된 함수 안에서만 사용이 가능하다.
그래야 컴포넌트가 마운트 됐을 때 asyncStorage에 있는 값을 불러온다.
그리고 바로 setState를 한다.
npm install @react-native-async-storage/async-storage
yarn add @react-native-async-storage/async-storage
useEffect(() => {
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");
setTodos(JSON.parse(resp_todos));
};
getData();
}, []);
const setCat = async (cat) => {
setCategory(cat);
await AsyncStorage.setItem("category", cat);
};
useEffect(() => {
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");
const resp_cat = await AsyncStorage.getItem("category");
setTodos(JSON.parse(resp_todos));
setCategory(resp_cat);
};
getData();
}, []);