Is it possible to access a different state within a action?
Scenario: I have two states:
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
?
Shared State
documentation answers the question:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With