FrontEnd/React Native

[react native] 스토리지 저장하기 asyncStorage

무무둥 2023. 2. 25. 23:53

웹 브라우저의 localStorage와 같이 동작하는 저장소 정도로 이해하면 된다....

 

https://docs.expo.dev/versions/v48.0.0/sdk/async-storage/

 

AsyncStorage

Expo is an open-source platform for making universal native apps for Android, iOS, and the web with JavaScript and React.

docs.expo.dev

# 패키지 설치
> npx expo install @react-native-async-storage/async-storage

실제 사용법은 아래 사이트를 참고한다.

https://react-native-async-storage.github.io/async-storage/docs/usage/

 

Usage | Async Storage

Async Storage can only store string data, so in order to store object data you need to serialize it first.

react-native-async-storage.github.io

 

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

const STORAGE_KEY = "@item";

export default function App() {
	// AsyncStorage를 사용하기 위해서 반드시 async-await 형태로 작성 해주어야한다.
	const save = async (toSave) => {
    	// key-value 형식으로 저장해 주어야 한다. value는 string 형태로 저장한다.
        // object를 저장하기 위해서 json 형식으로 변환
    	await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
  	};
    
    // 저장한 데이터를 가져온다.
    const load = async () => {
        const s = await AsyncStorage.getItem(STORAGE_KEY);
        JSON.parse(s);
    };
}

기본적으로 AsyncStorage 기능은 위와 같이 사용한다.

 

추가적으로 데이터를 저장/불러오는 부분은 자유롭게 작성하면 된다.