React-native 저장소 AsyncStorage

beablessing·2022년 1월 4일
0

React-Native

목록 보기
1/1
post-thumbnail

브라우저에서 로그인 유지 등 상태저장 장소로 사용한 Local 데이터 장소가 RN에는 없다.

이를 대체할 수 있는 2가지 방법이 존재
:: 앱 database에 상태 등을 저장할 수 있다.

  1. Sqlite

https://github.com/andpor/react-native-sqlite-storage

npm install --save react-native-sqlite-storage

  1. AsyncStorage
    npm i @react-native-community/async-storage

AsyncStorage를 이용하여 LocalStorage에 저장하거나 사용할 수 있다.

// 유저 닉네임 저장
AsyncStorage.setItem('nickname','User1', () => {
  console.log('유저 닉네임 저장 완료')
});
// 유저정보 (nickname, phonenumber) 저장
AsyncStorage.setItem('nickname',JSON.stringify({'nickname': 'User1', 'phonenumber','010-xxxx-xxxx'}), () => {
  console.log('유저정보 저장 완료')
});

// 유저 닉네임 불러오기
AsyncStorage.getItem('nickname', (err, result) => {
  console.log(result); // User1 출력
});
// 유저 닉네임 불러오기
AsyncStorage.getItem('nickname', (err, result) => {
  const UserInfo = Json.parse(result);
  console.log('닉네임 : ' + UserInfo.nickname); // 출력 => 닉네임 : User1 
  console.log('휴대폰 : ' + UserInfo.phonnumber); //  출력 => 휴대폰 : 010-xxxx-xxxx
});

*참고 )
JSON 이나 배열 형태 데이터의 경우 JSON.parseJSON.stringify로 저장해주어야 한다.

profile
프론트엔드 개발자

0개의 댓글