Reputation: 821
Let's say I have a list of products that can be filtered by type
when user selects a different type
from a dropdown (there are other filters users can set as well but they aren't relevant to this example).
I have State A that holds the currently filtered products. State B holds the currently selected type.
When user changes a type, I want it to also update the currently filtered products.
What is the proper way to do this?
Upvotes: 0
Views: 1532
Reputation: 8001
Assuming you don't want to / can't have selected type
value on State A, I'd suggest a Selector
on state A that depends on the state B values.
In state A:
@Selector([StateB])
static filterProducts(stateA: StateAModel, stateB: StateBModel) {
return stateA.products.filter(p => p.type === stateB.type);
}
This will be reevaluated whenever stateB changes (or state A by default in the current NGXS release). A further refined way would be having a type selector on state B.
In state B:
static @Selector()
selectedType(state: StateBModel) {
return state.type;
}
Then use that selector in state A:
@Selector([StateB.selectedType])
static filterProducts(stateA: StateAModel, selectedType: any) {
return stateA.products.filter(p => p.type === selectedType);
}
This way selectors will fire when the state changes and you don't need to add further actions.
Upvotes: 1