Resort Reducer
Open the src/app/store/reducers.ts file.
Initial State
Declare the initial state for the resort state:
export const initialResortsState = {
error: null,
loading: false,
resorts: []
};Reducer
Declare a reducer pure function that returns a new state object determined by an appropriate action:
export const resortReducer = (
state: State = initialResortsState,
action: ResortAction
): State => {
switch (action.type) {
case ResortActions.LoadResorts:
return {
...state,
loading: true
};
case ResortActions.LoadResortsFail:
return {
...state,
error: action.error,
loading: false
};
case ResortActions.LoadResortsSuccess:
return {
...state,
error: null,
loading: false,
resorts: action.resorts
};
default:
return state;
}
};- The
resortReducerfunction accepts two arguments: the current state, which defaults to the initial state that we declared previously, and the action that is being performed. - Note that the return type is a new
Stateobject. - Within our reducer, we
switchon theaction.typevalue. - For the
LoadResortsaction we return a new state with theloadingproperty set totrue. We can use this to toggle a loading indicator. - For the
LoadResortsFailaction we return a new state with theloadingproperty set tofalsealong with anerrorobject. - For the
LoadResortsSuccessaction we return a new state with theloadingproperty set tofalsealong with theresortsarray.
Collections
For now, we'll be storing the collection of resorts as an array in the state object.
We'll learn about the performance impact this might have and why we will use a Dictionary to store a collection of entities when using the @ngrx/entity library.
Update reducers
Open src/app/store/index.ts and specify the new resort property in the state object along with the resortReducer:
const reducers: ReducerMap = {
resort: resortReducer,
sidenav: sidenavReducer
};