Where to make API call and how to structure actions
Asked Answered
D

1

8

I've recently started migrating from ngrx to ngxs and had a design question of where I should be placing some of my calls.

In NGRX, I would create 3 actions for each interaction with an api. Something like:

GetEntities - to indicate that the initial api call was made GetEntitiesSuccess - to indicate a successful return of the data GetEntitiesFail - to indicate a unsuccessful return of the data

I would create an effect to watch for the GetEntities Action that actually called the API and handled the response by either calling the Success/Fail actions with the resultant payload.

In NGXS, do I make the api call from the store itself when the action occurs or is there some other NGXS object that I am supposed to use to handle those API calls and then handle the actions the same way I did in ngrx (by creating multiple actions per call)?

Derrek answered 6/2, 2019 at 15:54 Comment(0)
E
6

Most of the examples I have seen, and how I have used it is to make the API call from the action handler in the state, then when the API returns patch the state immediately.

Then after the patch call, you can dispatch an action to indicate success/failure if you need to. Something like this:

@Action(GetSomeData)
loadData({ patchState, dispatch}: StateContext<MyDataModel>, {payload}: GetSomeData) {

   return this.myDataService.get(payload.id)
   .pipe(
      tap((data) => {
        patchState({ data: data});
        // optionally dispatch here
        dispatch(new GetDataSuccess());
      })
   ); 
}  

This q/a might also be useful Ngxs - Actions/state to load data from backend

Electrojet answered 7/2, 2019 at 0:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.