Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngxs: Access different state within Action

Tags:

ngxs

Is it possible to access a different state within a action?

Scenario: I have two states:

  • FilterState
  • AppState

FilterState contains an action Filter, when the filter action is triggered, then the filterService is called with the payload of the action + with a value from the AppState.

@Action(Filter)
filter(ctx, action) {
  // HOW TO GET VALUE FROM AppState

  return this.filterService.filter(action, valueFromOtherStore).pipe(
    tap(data => {
    // Do something with result
    })
  );
}

How is it possible to retrieve values from a different state to apply this value to the second param of this.filterService.filter?

like image 704
Ratan Avatar asked Jul 16 '18 09:07

Ratan


1 Answers

Shared State documentation answers the question:

  • Docs: https://ngxs.gitbook.io/ngxs/advanced/shared-state

To get access to a different state selectSnapshot method on store can be used: this.store.selectSnapshot(PreferencesState.getSort)

Example

@State<PreferencesStateModel>({
  name: 'preferences',
  defaults: {
    sort: [{ prop: 'name', dir: 'asc' }]
  }
})
export class PreferencesState {
  @Selector()
  static getSort(state: PreferencesStateModel) {
    return state.sort;
  }
}
​
@State<AnimalStateModel>({
  name: 'animals',
  defaults: [
    animals: []
  ]
})
export class AnimalState {
​
  constructor(private store: Store) {}
​
  @Action(GetAnimals)
  getAnimals(ctx: StateContext<AnimalStateModel>) {
    const state = ctx.getState();
​
    // select the snapshot state from preferences
    const sort = this.store.selectSnapshot(PreferencesState.getSort);
​
    // do sort magic here
    return state.sort(sort);
  }
​
}
like image 76
Ratan Avatar answered Nov 11 '22 22:11

Ratan