34
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AsyncStorageはもういらない!react-native-storageを使ってみた!

Posted at

 alt

react-nativeのデータベースには、三つの選択肢がある。

  1. AsyncStorage
  2. react-native-storage
  3. realm

1のAsyncStorageは、react-native標準のデータベースだが、文字列しか保存出来ない!!!
なんと、Integer,Boolean,Arrayなどを保存するにはラッパーを書く必要がある。

3のrealmは、クエリを投げれて、一番複雑なことが出来るが、react-native-linkが必要になる。
出来ればnativeコードを使いたくないので、これも除外

2のreact-native-storageは、AsyncStorageの薄いラッパーで、わずか350行で書かれている。
しかし、AsyncStorageよりはるかに使いやすい

そこで、私はreact-native-storageを使うことにした。

使い方

まず、

yarn add react-native-storage

次にstorageを作成する。

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

const storage = new Storage({
  storageBackend: AsyncStorage
})

セーブ

keyと、dataを指定するだけ。objectとか、arrayをそのまま突っ込めるのが素晴らしい。

storage.save({
  key: 'someKey',
  data: {
    name: 'kabaya',
    age: 25,
    hasGirlFriend: false,
    array: [1,2,3],
    object: {foo: 'foo'}
  }
})

ロード

データのロードは一行で済む。keyを指定すると、objectが帰ってくる。

storage
  .load({key: 'someKey'})
  .then(res => console.log(res))
  .catch(err => console.warn(err))

結論

react-native-storageは、react-nativeのデータベースのデファクトスタンダード、
内部では、indexも貼っていてくれて、生でAsyncStorageを使うより、高速で、扱いやすい。
ぜひお試しあれ!

34
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?