-
TodoList에 AsyncStorage 사용하기React/React Native 2023. 1. 2. 12:18
웹에서는 LocalStorage, 앱에서는 AsyncStorage
https://react-native-async-storage.github.io/async-storage/docs/install/설치
npm install @react-native-async-storage/async-storage yarn add @react-native-async-storage/async-storage
사용하기
AsyncStorage는 비동기적으로 실행해야 하며, 즉 함수 안에서만 실행 할 수 있다.
import AsyncStorage from '@react-native-async-storage/async-storage'; // 사용하기 위해 import 해온다.
// 현재 최신 todos를 AsyncStorage에 저장 useEffect(() => { const saveTodos = async () => { await AsyncStorage.setItem('todos', JSON.stringify(todos)); // 배열인 data는 확실하게 json화를 시켜줘야 에러없이 잘 돌아간다. }; if (todos.length > 0) saveTodos(); // 글이 1개이상 있어야 saveTodos가 실행됨 }, [todos]); // todos가 변경될 때 마다 useEffect 실행 // 컴포넌트가 마운트 될 때 마다 실행 useEffect(() => { const getDate = async () => { const resp_todos = await AsyncStorage.getItem('todos'); // todos 배열 const resp_cat = await AsyncStorage.getItem('category') setTodos(JSON.parse(resp_todos)); setCategory(resp_cat); }; getDate(); }, []); // 카테고리 저장 const setCat = async (cat) => { setCategory(cat); await AsyncStorage.setItem('category', cat); // data type이 string이라 stringify 할 필요 없다. };
<StyledTouchNav onPress={() => setCat('js')} style={{backgroundColor: category === 'js' ? '#0FBCF9' : 'grey'}} > <StyleText>Javascript</StyleText> </StyledTouchNav> <StyledTouchNav onPress={() => setCat('react')} style={{backgroundColor: category === 'react' ? '#0FBCF9' : 'grey'}} > <StyleText>React</StyleText> </StyledTouchNav> <StyledTouchNav onPress={() => setCat('ct')} style={{backgroundColor: category === 'ct' ? '#0FBCF9' : 'grey'}} >
'React > React Native' 카테고리의 다른 글
React Native로 영화소개 서비스 만들기-1. UI 만들기(1) (0) 2023.01.03 TodoList와 firebase 연결 및 세팅 (0) 2023.01.02 React Native로 TodoList 만들기 (0) 2022.12.30 React Native 설치 및 로컬환경 작업부터 배포까지 (2) 2022.12.29