4
4

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.

世界一シンプルなReact-native + Reduxチュートリアル3

Last updated at Posted at 2018-04-30

前回までのチュートリアル
世界一シンプルなReactNativeチュートリアル1
世界一シンプルなReactNativeチュートリアル2

さあ前回作ったメモアプリはアプリを閉じるとメモが消えてしまう欠陥品だった。
今回はredux-persistでstoreを永続化(データベースに保存)してみよう。

redux-persistがあると何が嬉しいか?

今までは、データベースにデータを保存するには

1.reduxのstoreに保存する 
2.storeから値を呼び出す
3.データベースに保存

と言う3ステップが必要だった。
しかしredux-persistを使うことで、

1.reduxのstoreに保存する=同時にデータベースに保存される

になる!!!

つまりdatabaseへの読み書きの記述を一切しなくてよくなる。
このredux-persistがあるから私はreduxをreact nativeで使っている。
mobx-persistなどもあるが、starが少ない(泣)...
結局2018年のreact nativeはreduxを使わざるを得ないw

導入

redux-persistの導入ははとても簡単だ。まず
yarn add redux-persist
// npm i redux-persist
そして以下のように記述するだけだ。

// store.js
import { createStore } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import rootReducer from "./rootReducer";
import storage from "redux-persist/lib/storage";

const persistConfig = {    
  key: "root",             
  storage                  
};
  
const persistedReducer = persistReducer(persistConfig, rootReducer);
   
export const store = createStore(persistedReducer);
export const persistor = persistStore(store);

...終了だ。

なんと言う手軽さだろう。
もうメモアプリを閉じてもメモは消えないよ。やったね。

このredux-persist設定をすることで、保存先のDBを選べたり、保存しないstateをreducer単位で選ぶことも可能だ。
実は今回redux-persistを使ったことによりスマホのDBからstateの呼び出しがあるので、アプリの起動が遅くなっている。
がーん。
react native 標準のデータベースのasync storageは遅いことで有名だ。
工数を取れる人は、他のデータベースへと乗り換えよう。

redux-persistのREADMEを読めば大抵のことは出来るようになる。
(dbを低速なasyncStrageから変更したい。一部のstateだけdbに保存したいなど。)

これできみもReactNativeマスターだ。

4
4
3

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?