Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clean my form after a ngrx succeeded action?

Tags:

angular

ngrx

I have a reactive form:

const createFormGroup = (dataItem?: Usuario) => {
  if (dataItem) {
    return new FormGroup({
      id: new FormControl(dataItem.id),
      nome: new FormControl(dataItem.nome),
      cidade: new FormControl(dataItem.cidade)
    });
  }
  return new FormGroup({
    id: new FormControl(),
    nome: new FormControl(''),
    cidade: new FormControl('')
  });
};

This is my template:

<form (ngSubmit)="save()" [formGroup]="formGroup">
   <input formControlName="nome" type="text" class="form-control" id="inputName" placeholder="Nome">
   <input formControlName="cidade" type="text" class="form-control" id="exampleInputPassword1"
   <button id="my-element" type="submit" class="btn btn-primary">Complete
   </button>
</form>

After I click on "submit", I make a dispatch that save my data using a ngrx effect:

save() {
  const user = this.formGroup.value;
  if (user.id === null) {
    this.store.dispatch(createUser({ user: user }));
  } else {
    this.store.dispatch(updateUser({ user: user }));
  }
}

This is my effect:

public saveUser$ = createEffect(() =>
  this.actions$.pipe(
    ofType(createUser),
    switchMap((action) =>
      this.usuarioService.save(action.user).pipe(
        map(() => loadUsers()),
        catchError((error) => of(loadUsers()))
      )
    )
  )
);

Someone can tell me if have one way to clear my reactive when my effect don't go to catchError?

like image 791
veroneseComS Avatar asked Dec 05 '25 15:12

veroneseComS


1 Answers

  • If you want to do it ngrx way, call another action from your effect on the success.
saveUser$ = createEffect(() =>
    this.actions$.pipe(
        ofType(createUser),
        switchMap((action) =>
            this.usuarioService.save(action.user).pipe(
                map(() => {
                    loadUsers();
                    return new clearFormAction();
                }),
                catchError((error) => of(loadUsers()))
            )
        )
    )
);
  • Reset your form data to empty(initial state in general cases) in the reducer for clearFormAction().
case clearFormAction: {
    return {
        ...state,
        id: '',
        nome: '',
        cidade: ''
    };
}
  • Subscribe to the store form data in your component ngOnInit()
this.storeFormData$ = this.store.select(formData);
this.storeFormData.subscribe(formData => {
    this.formGroup.setValue(formData);
});
  • So whenever your this.usuarioService.save() is success your form will be cleared.
like image 103
Ravi Teja Vattem Avatar answered Dec 08 '25 03:12

Ravi Teja Vattem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!