LoginSignup
2
1

More than 3 years have passed since last update.

【ReactNative+Typescript】ローカルDBでRealmを使う

Last updated at Posted at 2020-04-07

概要

ReactNativeTypescriptのプロジェクトにローカルDBとしてRealmをインストール・使用する際のメモ。
環境は以下の通り。

  • node @10.15.0
  • react-native @0.61.5
  • typescript @3.5.3

インストール

nodeのバージョンが10.X系にする必要がある。

install --save realm

react-nativeのバージョンが0.59以下の場合は要link

iOSの場合

CocoaPods

cd ios
pod install

実装

import Realm from 'realm'

// スキーマ名
const HOGE_SCHEMA_NAME : string = 'HOGE';

// スキーマ定義
const HOGE_SCHEMA : Realm.ObjectSchema = {
    // スキーマ名
    name : HOGE_SCHEMA_NAME ,
    // 主キー(省略可)
    primaryKey : 'prop1',
    // プロパティ
    properties: {
        // 型のみ指定
        prop1 : 'int',
        // 型と初期値を指定
        prop2 : { type : 'string', default : 'hoge' },
    }
}

// データIF
interface Hoge {
    prop1 : number,
    prop2 : string,
}

// DB操作開始
Realm.open({
    schema : [HOGE_SCHEMA]
}).then((realm : Realm) => {
    // write()でトランザクションを開始する
    realm.write(() => {
        // primaryKeyを指定しているならcreate()はupsertとして働かせることもできる(その場合は第3引数にtrue)を渡す
        realm.create(HOGE_SCHEMA_NAME , { prop1: 0, prop2 : 'test' });
        // 削除はdelete()もしくはdeleteAll()
    });

    // objects(schemaName : string)でデータを取得
    const datas : Realm.Results<Hoge> = realm.objects(HOGE_SCHEMA_NAME);
});

参考

2
1
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
2
1