go to article

javascript/react.js

[React_Native] AsyncStorage 사용법

1. 설치

0.59 이전 버전의 리액트 네이티브에서는 설치 스킵

0.60 이후 버전의 리액트 네이티브

npm install --save @react-native-community/async-storage

설치 완료 후,

cd ios
pod install

리액트 네이티브 0.60 이후 버전은 라이브러리가 자동으로 연결
이전 버전의 리액트 네이티브에서는 다음 명령어로 라이브러리 연결 필요

react-native link @react-native-community/async-storage

 

2. 사용

Set

import AsyncStorage from '@react-native-community/async-storage';

...

AsyncStorage.setItem('token', 'save your token').then(() => {
  setter({
    key: 'value',
  });
  // do something more...
});

 

Get

import AsyncStorage from '@react-native-community/async-storage';

...

const getter = (): void => {
  AsyncStorage.getItem('token')
    .then((value) => {
      if (value) {
        setter({
          key: 'value',
        });
      }
      // do something more...
    })
    .catch(() => {
      setter(undefined);
      // do something more...
    });
};

 

Remove

import AsyncStorage from '@react-native-community/async-storage';

...

AsyncStorage.removeItem('token');