Context 를 사용하면 앱이 꺼지면 데이터가 사라진다. 핸드폰 로컬에 데이터를 저장하여 저장한다.

공식 문서 https://react-native-async-storage.github.io/async-storage/docs/install


1. 설치하기

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

2. AsyncStorage 다루는 법 살펴보기

const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('@storage_Key', value)
  } catch (e) {
    // saving error
  }
}
const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

3. 나만의 API 만들기

src/api/AsyncStorage.ts 파일 만들기

import AsyncStorage from "@react-native-async-storage/async-storage"

const setStorage = async (key: string, value: string | JSON) => {
    try {
        const jsonValue = typeof value === "string" ? value : JSON.stringify(value)
        await AsyncStorage.setItem(key, jsonValue);
    } catch (e) {
        console.log(e)
    }
}

const getStorage = async (key: string) => {
    try {
        const jsonValue = await AsyncStorage.getItem(key)
        if (typeof jsonValue === "string")
            return jsonValue;

        return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch (e) {
        console.log(e)
    }
}

const rmStorage = async (key: string) => {
    try {
        await AsyncStorage.removeItem(key)
    } catch (e) {
        console.log(e)
    }
}

export {setStorage, getStorage, rmStorage}
const asyncKey = {
		userToken: "userToken"
}

export {asyncKey}