Redirect to page after dispatching an action (ngredux)

126 views Asked by At

I have a project with angular 6 + ngredux and I want an advice for the next situation:

  • I have an overview details page (read-only information), filled with data from the app state. In this page, I have some buttons which open other pages (here we have some forms - in these forms the user can edit some fields).
  • When the user saves the data, he should return to the overview details page. Since we are using ngredux and we update the values from the app state, we are handling this in the component using a component like:

    onSubmit(){
    this.actionsCreator.save(this.model);
    const route = 'details/' + this.objId;
    this.router.navigate([route]);
    } 
    

The problem that we encountered is that if the "save" method takes 2-3 seconds in the API, the user is redirected first, and after that, the model is saved and updated in the app state (this is normal - we do the redirect in a wrong way).

For dispatching the actions we are using a custom middleware.

return next => action => {
const {type, callApi, shouldCallApi, success = function () { }} = action;
if (!shouldCallApi) { return next(action);}
if (typeof callApi !== 'function') {throw new Error('Expected callApi to be a function');}
if (typeof shouldCallApi !== 'function') {throw new Error('Expected shouldCallApi to be a function');}
if (!shouldCallApi(getState())) {return;}

return callApi().subscribe(response => {
    success(response);
    return dispatch({type: type,payload: response || null});
    });
};

Therefore, I want a recommendation for how to handle this kind of situations. Should we inject the router in the actionsCreator service (is this the right way to go) and on dispatch make the redirect (in case of success)? Or from the reducer? Or only from the component?

0

There are 0 answers