Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 49107

Ngrx store & effects using Storage?

$
0
0

@ozexpert wrote:

Having a hard time learning Ngrx effects. I’m using ngrx/store to manage my state. However, I’d like to have Ngrx effects to handle saving to Ionic Storage when state is changed. However, I’m not sure how I can do that.

I have the following code, but dispatching with type UPDATE_SETTINGS won’t get the changed state, so I can’t really change it in the storage. Does anyone have a similar example of using ngrx/effects? anything similar to this would help. Thanks!

import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Actions, Effect } from "@ngrx/effects";
import {
  GET_SETTINGS,
  UPDATE_SETTINGS,
  UPDATE_SETTINGS_SUCCESS,
  Action,
  AppState
} from '../_reducers/settings.reducer';
import { StorageProvider } from '../providers/storage/storage';
import { Observable } from "rxjs";

const storageKey = 'settings';

@Injectable()
export class SettingsEffects {
  constructor(
    private storage: StorageProvider,
    private actions$: Actions,
    private store$: Store<AppState>
  ) {}

  @Effect() get$ = this.actions$
    .ofType(GET_SETTINGS)
    .mergeMap((action: any) => Observable.fromPromise(this.storage.get(storageKey))
        .map(data => ({ type: UPDATE_SETTINGS, payload: data }))
        .catch(() => Observable.of()))
    .catch(() => Observable.of());

  @Effect() update$ = this.actions$
    .ofType(UPDATE_SETTINGS)
    .switchMap(() => {
      return Observable.of({ type: "UPDATE_SETTINGS_SUCCESS" })
    });

  @Effect() updateSuccess$ = this.actions$
    .ofType(UPDATE_SETTINGS_SUCCESS)
    .do(() => {
      console.log('update settings success called');
    })
    .withLatestFrom(this.store$)
    .switchMap(([ payload, store ] : any) => {
      return Observable.fromPromise(this.storage.set(storageKey, store.settings))
        .catch(() => Observable.of())
    })
    .catch(() => Observable.of());
}

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 49107

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>