Skip to content

Commit

Permalink
fix(angular): Add debounce to PlanerNameForm submit button to prevent…
Browse files Browse the repository at this point in the history
… joining multiple times
  • Loading branch information
axeleroy committed Dec 15, 2023
1 parent c3443b9 commit bc4fc01
Showing 1 changed file with 20 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,32 +1,47 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Component, EventEmitter, Input, OnDestroy, Output } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { UserInformationService } from '../user-info/user-information.service';
import { TranslocoDirective } from '@ngneat/transloco';
import { debounceTime, Subject, Subscription } from "rxjs";

@Component({
selector: 'shpp-player-name-form',
templateUrl: './player-name-form.component.html',
standalone: true,
imports: [TranslocoDirective, ReactiveFormsModule]
})
export class PlayerNameFormComponent {
export class PlayerNameFormComponent implements OnDestroy {
formGroup: FormGroup;

@Input()
join = false;
@Output() validated = new EventEmitter<void>();

private subscription?: Subscription;
private subject: Subject<void>

constructor(private fb: FormBuilder,
private userInformation: UserInformationService) {
this.formGroup = this.fb.group({
username: [ this.userInformation.getName(), [Validators.required, Validators.minLength(1)]]
});

this.subject = new Subject<void>();
this.subscription = this.subject
.pipe(debounceTime(1000))
.subscribe(() => {
const username = this.formGroup.get('username')?.value;
this.userInformation.setName(username);
this.validated.emit();
});
}

ngOnDestroy(): void {
this.subscription?.unsubscribe();
}

setUsername(): void {
const username = this.formGroup.get('username')?.value;
this.userInformation.setName(username);
this.validated.emit();
this.subject.next();
}

}

0 comments on commit bc4fc01

Please sign in to comment.