Cretezy / redux_persist

Persist Redux State
https://pub.dartlang.org/packages/redux_persist
MIT License
130 stars 41 forks source link

Proper way to handle exceptions in persistor.load? #30

Closed psyanite closed 5 years ago

psyanite commented 5 years ago
    redux_persist_flutter: ^0.8.0-rc.0
    redux_persist: ^0.8.0-rc.0

The Readme has no indication on how to handle an exception on persistor.load, so I wrote this try catch because when there is an exception on persistor.load, the app freezes and stays white unless I put in the try catch. If there is a better way to write this, please let me know I would really appreciate it.

void main() async {
  final persistor = Persistor<AppState>(storage: FlutterStorage(), serializer: JsonSerializer<AppState>(AppState.rehydrate));

  var initialState;
  try {
    initialState = await persistor.load();
  }
  catch (e) {
    initialState = null;
  }

  List<Middleware<AppState>> createMiddleware() {
    return <Middleware<AppState>>[
      thunkMiddleware,
      persistor.createMiddleware(),
      LoggingMiddleware.printer(),
    ]
      ..addAll(createHomeMiddleware())
      ..addAll(createMeMiddleware());
  }

  final store = Store<AppState>(
    appReducer,
    initialState: initialState ?? AppState(),
    middleware: createMiddleware(),
  );

  runApp(Main(store: store));
}
Cretezy commented 5 years ago

Your JSON decoder function (AppState.fromJson) must be able to accept null, you'll most likely want to return an empty state.

A try...catch is the proper way to handle this.