react native 친해지자! - todo app 구현하기 2

lionloopy·2024년 12월 28일

리액트 네이티브

목록 보기
5/5
post-thumbnail

AsyncStorage

  • 이제 todo를 만들었을 때 이걸 핸드폰에 저장해야 reload했을 때 남아있을 수 있다!
    그럼 이걸 어떻게 핸드폰에 저장해둘건가? -> AsyncStorage 활용
  1. 설치
npm install @react-native-async-storage/async-storage
  1. 활용
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;
  };
  • async await을 사용해주고

setItem

setItem으로 AsyncStorage에 데이터를 넣어준다.
이 때 KEY를 만들어두고, 이 키를 활용해서 데이터를 꺼내야한다.
상수화해놓으면 good!

getItem

getItem으로 AsyncStorage에 넣어둔 데이터를 꺼내준다.
이 때 KEY를 활용해서 꺼내준다.

추가

  • 데이터를 넣어줄 땐 JSON.stringify로 string화 해주고,
  • 데이터를 꺼내줄 땐 JSON.parse로 object화 해준다.

trouble shooting

  • AsyncStorage가 잘 동작이 안 되는 것 같았다.
    -> 일단 try, catch문을 꼭 넣어줘서 디버깅을 하고
    -> 에러 문구를 확인해보니 설치가 잘 되지 않았고, import 구문이 틀렸다.
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 구문을 변경해주었더니 정상작동했다.

  • loadTodos 함수는 useEffect로 실행되고 있는데, 데이터가 null이면 오류가 떴다.
    -> 아래와 같은 조건문을 넣어주어 해결했다.
s !== null ? setTodos(JSON.parse(s)) : null;

Alert API

  • 팝업창 실행시키기!

alert

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 함수를 넣어주면 해당 버튼에 해당 함수가 동작한다.

prompt

  • ios에서만 작동함
Alert.prompt("hello")
profile
기록은 담백하게, 성장은 빠르게! 🐘

0개의 댓글