Loadable-State
This package is to help you model http request state. It's an add-on to redux/ngrx
Why use this package?
Reduce boilerplate and better code.
I wrote details in this 5-min blog: https://blog.angularindepth.com/handle-api-call-state-nicely-445ab37cc9f8
Install
npm install loadable-state
Get Started
Let's assume we need to send an http request to get a list of today's news. And we are using Angular/ngrx.
Step1: Model your state
In this way, News
model has 4 fields: news
, loading
, success
and error
.
Step2: Create your actions
Step3 Reducer (Most Important)
// base reducer should only update non-loadable states// withLoadable enhances baseReducer to update loadable state
baseNewsReducer
handles non-loadable states (i.e. entities)
newsReducer
will actually apply withLoadable
enhancer to baseReducer
to give some “magic” to baseReducer
, and the “magic” is to handle the 3 loadable states changes automatically.
####Step4 Effects
loadNews = this.actions$.pipe ofTypeNewsActionsTypes.Load, switchMapthis.http.get'some url', mapnew LoadNewsSuccess, catchErrorofnew LoadNewsErrorerror;
Checkout this StackBlitz for a complete example. https://stackblitz.com/github/zhaosiyang/loadable-example