Reputation: 1826
I need to allow the user to see all other users from his location. It means that if the user lives in Israel then by clicking on "my location" he need to see all the users from Israel.
The location of the user can be fetched using an http call So when the user clicks on "my Location" button the first action is dispatched which is "GetLocation". This action has an effect that operates the GetLocationSuccess Action with the Location as a payload.
Now I want to operate the GetDirectory action and it also has an effect by the name of GetDirectorySuccess which get the current locationusing the withLatestFrom rxjs operator and it also has an effect because there is another http get call.
So now is the problem. At the container application I am dispatching the GetLocation and immediately dispatching the GetDirectory Action (the one that has an effect that gets the current location with getLatestFrom) but the latest action is happening before the effect of the first action has dispatched the "getLocationSuccess" and I am not getting users that are filtered by the location.
Should I use another effect that listens to the "GetLocationSuccess" action or is there a better way to dispatch an action after I am positive that the previous effect has finished dispatching its effect and updating the data.
What is the best way to act if an Action need to get data from a http call before it is dispatched to operate its own http call.
Upvotes: 1
Views: 68
Reputation: 837
I would create 3 actions for each of your http calls to avoid any race conditions. A Load, LoadFail and LoadSuccess. Then you can easily create effects that listen for the success of each one of those requests and handle them appropriately.
So you could use something like the following:
loadLocaton$ = createEffect(() => this.actions$.pipe(
ofType(locationActions.Load),
mergeMap(() => this.locationService.get().pipe(
map(location => locationActions.LoadSuccess({location})),
catchError(err => of(locationActions.LoadFail(err)))
))
));
getDirectory$ = createEffect(() => this.actions$.pipe(
ofType(locationActions.LoadSuccess),
map((location) => directoryActions.Load(location))
));
Upvotes: 2