15.8.5 AsyncStorage로 인증 상태 유지하기

    앱을 종료한 후 재시작했을 때 인증 상태를 유지하는 기능을 구현해봅시다. 이전에 사용해본 AsyncStorage를 사용하여 구현하면 됩니다.

    이 라이브러리를 설치해주세요. iOS 환경이라면 라이브러리를 설치한 후 npx pod-install 명령어를 실행해야 합니다.

    $ yarn add @react-native-async-storage/async-storage

    이 라이브러리는 네이티브 코드의 의존성이 있기 때문에, 라이브러리 설치가 끝나면 yarn ios 또는 yarn android를 한 번 더 입력하여 앱을 다시 빌드하세요.

    다음으로 최상위 디렉터리에 storages 디렉터리를 만들고, authStorage.ts 파일을 생성하여 다음 코드를 작성하세요.

    storages/authStorage.ts

    import AsyncStorage from '@react-native-async-storage/async-storage';
    import {AuthResult} from '../api/types';
    
    const key = 'auth';
    
    const authStorage = {
      async get() {
        const rawData = await AsyncStorage.getItem(key);
        if (!rawData) {
          return null;
        }
        try {
          const data: AuthResult = JSON.parse(rawData);
            return data;
          } catch (e) {
            return null;
          }
      },
      set(authResult: AuthResult) {
        return AsyncStorage.setItem(key, JSON.stringify(authResult));
      },
      clear() {
        return AsyncStorage.removeItem(key);
      },
    };
    
    export default authStorage;

    타입 지원을 위해 AsyncStorage의 기능들을 한번 추상화한 authStorage라는 객체를 만들어서 내보내줬습니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.