npm install @react-native-async-storage/async-storage
import AsyncStorage from "@react-native-async-storage/async-storage";
const STORAGE_KEY = "@todos";
const saveTodos = async (toSave) => {
try {
const s = JSON.stringify(toSave);
await AsyncStorage.setItem(STORAGE_KEY, s);
} catch (error) {
console.error("Error saving todos:", error);
}
};
const loadTodos = async () => {
const s = await AsyncStorage.getItem(STORAGE_KEY);
s !== null ? setTodos(JSON.parse(s)) : null;
};
setItem으로 AsyncStorage에 데이터를 넣어준다.
이 때 KEY를 만들어두고, 이 키를 활용해서 데이터를 꺼내야한다.
상수화해놓으면 good!
getItem으로 AsyncStorage에 넣어둔 데이터를 꺼내준다.
이 때 KEY를 활용해서 꺼내준다.
Error saving todos: [Invariant Violation: AsyncStorage has been removed from react-native core. It can now be installed and imported from '@react-native-async-storage/async-storage' instead of 'react-native'. See https://github.com/react-native-async-storage/async-storage]
-> 따라서 재설치하고, import 구문을 변경해주었더니 정상작동했다.
s !== null ? setTodos(JSON.parse(s)) : null;
Alert.alert("hello")
Alert.alert("Delete To Do?", "Are you sure?", [
{ text: "cancel" },
{
text: "ok",
onPress: async () => {
const newTodos = { ...todos };
delete newTodos[id];
setTodos(newTodos);
await saveTodos(newTodos);
},
},
]);
이런식으로 활용할 수 있는데,
처음 title ("Delete To Do?")는 alert의 가장 첫 title이고,
두번째 title ("Are you sure?")는 alert의 두번째 desc이고,
그 다음에 배열 형태로 버튼의 option을 넣을 수가 있다.
string 넣고 onPress 함수를 넣어주면 해당 버튼에 해당 함수가 동작한다.
Alert.prompt("hello")