ngxtension / ngxtension-platform

Utilities for Angular
https://ngxtension.netlify.app/
MIT License
592 stars 87 forks source link

[NEW FEATURE] Stateful functions #354

Open skoropadas opened 5 months ago

skoropadas commented 5 months ago

Hello guys, recently I created and started using a function that I think can be useful as part of this library.

The utility is quite handy when working with forms and requests like PUT, PATCH, POST, DELETE, i.e., when you need to perform some action on the backend while displaying its state to the user.

StatefulFn

This utility creates a function based on the passed function that contains the execution state based on the new signal API.

Creating a stateful function

This way you can create a function whose state you are interested in:

@Component()
class MyComponent {
  submit: StatefulFn;

  constructor() {
    this.submit = createStatefulFn(async () => {
      await firstValueFrom(this.httpClient.post(url));
    })
  }
}

And here's how you can use it in the template:

<form>
  <button (click)="sumbit()" [disabled]="submit.pending()">Submit</button>

  @if (submit.error(); as error) {
    {{ error.message }}}
  }
</form>

Let me know if you're interested and then I'll create a PR.

ajitzero commented 5 months ago

Duplicate of #56 in terms of usage in the template.