0

I have a NGRX Effect that saves a report, after the report is saved I want to reset the form and display a notification that the report was saved.

Below is an example of the store dispatching a effect to save the report and inject it into the store.

After it was saved and inserted, I want to reset the form and display a notification to the user.

onSubmit(): void {
  // Gather the fields from the form and
  // dispatch the new report event which will
  // save the report and insert it into the store
  const formModel = this.reportForm.value;
  this.store.dispatch(new AddReport(formModel));

  // After the report is saved, reset the form and
  // display a notification to the user it was saved
  this.reportForm.markAsPristine();
  this.snackbar.open('Report Saved!', null, { duration: 700 });
}

The issue is I want to only reset the form and show the notification if the report was saved by the backend. Whats the best way to accomplish this.

Meeker
  • 5,979
  • 2
  • 20
  • 38
amcdnl
  • 8,470
  • 12
  • 63
  • 99

1 Answers1

2

An effect is supposed to return a new action.

You have the effect make the API call and then if it is successful, you return an action that will hit the reducer to reset the form and then also call an affect to send the notification.

Basic Setup

reducers:
   successfullSubmit:
     const state = state.form = resetedform
     return state

effects
   formSubmit
     api.submitform
       on success return successfullSubmit
     catch
       on fail return submitFail
   successFullSubmit
     display notification

This is how the effect might be written for form submit

  @Effect()
  formSubmit$: Observable<Action> = this.actions$
    .ofType(actions.formSubmit)
    .map(toPayload)
    .switchMap(formStuffs =>
      this.api.submitForm(formStuffs)
        .map(() => new FormSubmitSuccess())
        .catch(error => of(new FormSubmitError(error))) 
    ); 
Meeker
  • 5,979
  • 2
  • 20
  • 38