As a beginner in ngrx and Angular development, I am exploring how to manage a collection of trades in my store. An effect is set up to listen for LoadTradeRequest, which triggers an HTTP request to fetch Observable data and then either dispatches a LoadTradeSuccess or LoadTradeFailure action based on the response.
@Effect()
loadTrade$: Observable<Action> = this.actions$.pipe(
ofType(ActionTypes.LoadTradeRequest),
mergeMap((action: actions.LoadTradeRequest) =>
this.remoteApiService.loadTrade(action.payload).pipe(
map(trade => new actions.LoadTradeSuccess(trade)),
catchError(err => of(new actions.LoadTradeFailure(err)))
)
);
In order to handle the LoadTradeSuccess action, a reducer function is implemented to add the loaded Trade to the existing state in the store.
case ActionTypes.LoadTradeSuccess: {
return { ...state, trades: [...state.trades, action.payload] };
}
The current State is declared as:
trades: Trade[];
Everything is functioning smoothly at this point. Now, the requirement is to modify the State so that the trades collection is organized with a unique identifier provided in the action payload of LoadTradeRequestAction.
Updated State Structure:
trades: DictionaryItem<string, Trade>[];
Here's the structure of DictionaryItem interface:
export interface DictionaryItem<K, V> { 0: K; 1: V; }
I am seeking guidance on how to pass a specific property from the triggering action to the subsequent action along with the HTTP response data. Below is a non-functional code snippet intended to illustrate the desired outcome:
@Effect()
loadTrade$: Observable<Action> = this.actions$.pipe(
ofType(ActionTypes.LoadTradeRequest),
mergeMap((action: actions.LoadTradeRequest) =>
this.remoteApiService.loadTrade(action.payload).pipe(
map(trade => new actions.LoadTradeSuccess({**action.payload.UniqueIdentifier**, trade})),
catchError(err => of(new actions.LoadTradeFailure(err)))
)
)