ngrx: predictable state changes with example
Here is an example of how predictable state changes can be implemented using ngrx in an Angular application.
Let’s say we have a feature state for a shopping cart in our application. The state interface might look something like this:
export interface CartState {
products: Product[];
total: number;
}
In this state, we have an array of products and a total price.
To ensure that state changes are predictable, we should define strict rules for how the state can be modified. This can be achieved through the use of actions and reducers.
First, we define actions for each possible state change. For example, here is an action for adding a product to the cart:
export class AddToCart implements Action {
readonly type = CartActionTypes.AddToCart;
constructor(public payload: Product) {}
}
This action has a type and a payload, which is the product being added to the cart.
Next, we define a reducer to handle this action:
export function cartReducer(state: CartState, action: CartActions): CartState {
switch (action.type) {
case CartActionTypes.AddToCart:
return {
...state,
products: [...state.products, action.payload],
total: state.total + action.payload.price
};
default:
return state;
}
}
This reducer takes the current state and the action as input, and returns a new state based on the action. In this case, when an AddToCart
action is received, the reducer creates a new state with the product added to the products
array and the total price updated.
By defining strict rules for state changes using actions and reducers, we can ensure that our state remains predictable and consistent throughout the application. This makes it easier to reason about the behavior of our application and to maintain it over time
BONUS BELOW
If you are new to the web development and hustling for bread and butter due to low income, Please check out the below link
Live Chat Jobs — You have to try this one at home