Prevent API requests to the Backend on NgRx or FirstValueFrom

ctrl/m
0


Effects

Actions can be dispatched through effects to modify the state. One useful application of effects is to prevent multiple API requests by caching the data. For instance, we can check if the piece of state related to the service already contains data. Assuming the information will not change, we can use any flattening strategy, such as mergeMap(), switchMap(), exhaustMap(), or concatMap().

#actions: Actions = inject(Actions); #http: HttpClient = inject(HttpClient); #store: Store<AppState> = inject(Store); #deserializeServices: DeserializeService = new DeserializeService();


load$ = createEffect(() =>
this.#actions.pipe(
ofType(fromServiceActions.getServicesFromBE),
concatLatestFrom(() =>
this.#store.select(fromServiceSelectors.selectServiceList)
),
mergeMap(([action, services]) =>
services.length
? of({
data: services,
})
: this.#http.get<IServiceResponse>(action.url)
),
pipe(
map((response) =>
fromServiceActions.setServiceToStore({
Services: this.#deserializeServices.deserialize(
response. data
),
})
),
)
)
);


firstValueFrom

Another way to prevent API requests is to use the firstValueFrom function
from rxjs and return a promise that resolves as soon as the first value
arrives from the observable.

public async loadServices() {
const existingServices = await firstValueFrom(this._services$);
if (existingServices.length) {
console.log('already has services');
return;
}
this.store.dispatch(
fromServiceActions.getServicesFromBE({
url: `${BASE_API}/${WEB_API_SERVICES}`,
})
);
}


In conclusion, preventing multiple API requests by caching data is a useful
application of effects. By checking if the piece of state related to the
service already contains data, we can use any flattening strategy to prevent
unnecessary API requests.

Additionally, the firstValueFrom function from rxjs
can also be used to prevent API requests to the backend. By implementing these
techniques, we can improve the performance of our application and provide a
better user experience.

If you need any corrections or further assistance, please don't hesitate to
let me know.

SHALOM!
Tags:

Post a Comment

0Comments

Post a Comment (0)