How can I receive an HTTP response in the component where I dispatch the action. After the action returns the status of 200 if I console log the response I am getting the entire state's data not the actual HTTP response from my API. There are certain scenarios where I am getting dynamic success messages from API after success, which I have display using toast from my component
How can I get the actual response inside my component after dispatching an action?
Component.ts
loadHolidays() {
const param = {
holidayFor: 1,
userId: 12
};
this._store
.dispatch(new FetchHolidays(param))
.pipe(
catchError((error) => {
throw error;
})
)
.subscribe({
next: (result) => {
console.log(result);
//result returns entire state not the actual HTTP response
}
});
}
Store.ts
@Action(FetchHolidays)
fetchAllHolidays(
ctx: StateContext<CalendarStateModel>,
{ param }: FetchHolidays
) {
return this._http.post('endpoint', param).pipe(
tap((apiResult) => {
const data = apiResult.response.data;
const holidays = data.holidayLists as IHoliday[];
ctx.patchState({
holidaysList: holidays
});
})
)
}
You can't do it in this way, because the dispatch function returns an observable (of the entire state) "that can be used to respond to the completion of each of these actions".
I think it's better in your use-case to use a service at the top-level of your application to handle showing the toast base on the message and status (success/failed) that passed to service, which can be called from everywhere in your project (e.g. in your state).
But anyway, if you need the result to be in the state, and at the time you need to use it in the component, then you have to store the response in the state, side by side with result, then access it in the component using the selector, like the following:
state.ts
@Selector()
static holidaysResponse(state: CalendarStateModel) {
return state.response;
}
@Action(FetchHolidays)
fetchAllHolidays(
ctx: StateContext<CalendarStateModel>,
{ param }: FetchHolidays
) {
return this._http.post('endpoint', param).pipe(
tap((apiResult) => {
const data = apiResult.response.data;
const holidays = data.holidayLists as IHoliday[];
ctx.patchState({
holidaysList: holidays,
response: apiResult.response,
});
})
);
}
component.ts
loadHolidays() {
const param = {
holidayFor: 1,
userId: 12,
};
this._store
.dispatch(new FetchHolidays(param))
.pipe(
catchError((error) => {
throw error;
})
)
.subscribe({
next: () => {
// get the holidayResponse after the action completed:
const response = this._store.selectSnapshot(
CalendarState.holidaysResponse
);
},
});
}