Is there any example of using effects (like ngrx-effects) with this library. If yes, could you please provide the link? Thanks.
( {NgRx}.reducer.ts + {NgRx}.effects.ts ) ≈ {NGXS}.state.ts
I. NGRX
@Injectable()
export class MovieEffects {
@Effect()
loadMovies$ = this.actions$
.pipe(
ofType('[Movies Page] Load Movies'),
mergeMap(() => this.moviesService.getAll()
.pipe(
map(movies => ({ type: '[Movies API] Movies Loaded Success', payload: movies })),
catchError(() => EMPTY)
))
)
);
constructor(
private actions$: Actions,
private moviesService: MoviesService
) {}
}
II. NGXS
@State({ .. })
export class MoviesState {
constructor(private moviesService: MoviesService) {}
@Action({ type: '[Movies Page] Load Movies' })
public loadMovies(ctx: StateContext): Observable<Movie[]> {
return this.moviesService.getAll().pipe(
map((movies) => ctx.setState(movies)),
catchError(() => EMPTY)
);
}
}
@splincode thanks for your response. Isn't loadMovies a reducer? If yes, isnt it supposed to be a pure function? Would be really great if you could explain this.
@goodmite
NGRX != NGXS
NGRX != Redux (library in React)
Redux is a pattern, predictable state container. How this container will be arranged depends on the implementation.
@goodmite The closest thing in NGXS to NGRS Effects is Action Handlers. See the docs here:
https://ngxs.gitbook.io/ngxs/advanced/action-handlers
Note that you would have to subscribe and dispatch the resultant action.
Although this is possible it is not really the normal way to do it with NGXS.
@goodmite
NGRX != NGXS
NGRX != Redux (library in React)Redux is a pattern, predictable state container. How this container will be arranged depends on the implementation.
The downside of not having pure functions as an action handler is that we cannot just replay the same actions with the same payload to get the same state.
In the first example of NGRX, you can see that if we dispatch two actions[Movies Page] Load Movies and [Movies API] Movies Loaded Success then we will get the same state. But in NGXS, we can't just do it because our action handler will call the Rest Service end-point every time we dispatch an action.
Most helpful comment
The downside of not having pure functions as an action handler is that we cannot just replay the same actions with the same payload to get the same state.
In the first example of NGRX, you can see that if we dispatch two actions
[Movies Page] Load Moviesand[Movies API] Movies Loaded Successthen we will get the same state. But in NGXS, we can't just do it because our action handler will call the Rest Service end-point every time we dispatch an action.