Update State when another State Changes

1.2k Views Asked by At

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?

  • I could call a 'set' action on State A from State B whenever State B is set
  • I could call a 'set' action on both State A and State B when a user sets State B
  • I could listen to State B in State A and update State A when State B changes
  • I could just have the type in State A as well, but I use the type for other separate states for other features as well
1

There are 1 best solutions below

4
On

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.