[React Native] reactNative AsyncStorage와 mmkv 사용방법

RuLu·2024년 12월 8일

React-Native

목록 보기
5/13
post-thumbnail

Async Storage

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

AsyncStoarge란?

브라우저의 localStorage처럼 key-value기반으로 로컬에 데이터를 저장할 수 있게 해주는 라이브러리.

localstorage와 마찬가지로, 문자열 데이터만 사용이 가능하기 때문에 JSON.parse 메서드의 사용이 필요하다.

다만 localStorage와 달리 비동기 처리가 필요하다.

설치방법

npm install @react-native-async-storage/async-storage
cd ios && pod install && cd ../

사용방법

저장하기

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

//스토리지에 저장
export const setStorageItem = async (
  key: YYYYMMDD,
  value: Omit<Diary, 'id'>,
) => {
  try {
    const res = await AsyncStorage.getItem(key);
    
 //value가 객체일 경우 아래처럼 경우를 나눠서 해야 에러 발생안함
    if (!res) {
      await AsyncStorage.setItem(
        key,
        JSON.stringify([
          {
            id: `${key} ${generateUuid()}`,
            title: value.title,
            date: value.date,
            day: value.day,
            content: value.content,
          },
        ]),
      );

      return;
    }

    const parseRes: Diary[] = JSON.parse(res);

    const newValue = [
      ...parseRes,
      {
        id: `${key} ${generateUuid()}`,
        title: value.title,
        date: value.date,
        day: value.day,
        content: value.content,
      },
    ];

    await AsyncStorage.setItem(key, JSON.stringify(newValue));
  } catch (e) {
    throw e;
  }
};

값 가져오기

export const getStorageItem = async (key: string) => {
  try {
    const res = await AsyncStorage.getItem(key);
    const parseRes: Diary[] = JSON.parse(res || '[]');

    return parseRes;
  } catch (e) {
    throw e;
  }
};

모든 키와 값 가져오기

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

export const getAllStorageItem = async () => {
  try {
  // 스토리지 모든 키 가져오는 API
    const keys = await AsyncStorage.getAllKeys();

//다중 키에 대한 키-값 배열 가져오는 API
    const values = await AsyncStorage.multiGet([...keys]);

    const allDiary: Diary[] = [];

    values.forEach(pair => {
      const [_, value] = pair;

      if (value) allDiary.push(...(JSON.parse(value) as Diary[]));
    });

    return allDiary;
  } catch (e) {
    throw e;
  }
};

스토리지 비우기


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

export const clearStorage = async () => {
  try {
    await AsyncStorage.clear();
  } catch (e) {
    throw e;
  }
};

MMKV

https://github.com/mrousavy/react-native-mmkv

mmkv란?

React Native를 위한 매우 빠른 키/값 스토리지 라이브러리이다.

get 및 set 문자열, 논리 값 및 숫자를 완전 동기식 호출이 가능하다.

모든 것이 C++ 로 작성 되었기 때문에 고성능이다. 약 AsyncStorage보다 30배 빠르다.

단, C++ 베이스 라이브러리이기 때문에 버그가 있더라도 확인하기 어려울 수 있다.

설치방법

npm install react-native-mmkv
cd ios && pod install && cd ../

사용방법

인스턴스 생성

mmkv를 사용하기 위해서는 인스턴스를 생성해야한다. 용도에 따라 서로 다른 mmkv 스토리지를 사용하는 것도 가능하다. 이는 공식문서에 자세히 설명되어있다.

import {MMKV} from 'react-native-mmkv';

export const storage = new MMKV();

저장하기

AsyncStoarge는 async/await 사용하고 try-catch 로 감싸줬지만 mmkv는 그러지 않아도 된다.

const handleSetStorageItem = (key: YYYYMMDD, value: Omit<Diary, 'id'>) => {
    const res = storage.getString(key);

    const newDiary: Diary = {
      id: `${key} ${generateUuid()}`,
      title: value.title,
      date: value.date,
      day: value.day,
      content: value.content,
    };

    if (!res) {
      storage.set(key, JSON.stringify([newDiary]));
    } else {
      const parseRes: Diary[] = JSON.parse(res);

      const newValue = [...parseRes, newDiary];

      storage.set(key, JSON.stringify(newValue));
    }

    return newDiary;
  };

가져오기

  const handleGetStorageItem = (key: YYYYMMDD) => {
    const res = storage.getString(key);
    const parseRes: Diary[] = JSON.parse(res || '[]');

    return parseRes;
  };

모든 키에 대한 값 가져오기

const handleGetAllStorageItem = () => {
    const keys = storage.getAllKeys();

    const allDiary: Diary[] = [];

    keys.forEach(key => {
      const value = storage.getString(key);

      if (value) {
        allDiary.push(...(JSON.parse(value) as Diary[]));
      }
    });

    return allDiary;
  };

스토리지 비우기

  const handleClearStorage = () => {
    storage.clearAll();
  };
profile
프론트엔드 개발자 루루

0개의 댓글