Adding examples to blaze

This commit is contained in:
Gabriel Grubba
2024-03-14 17:17:40 -03:00
parent a7a4e28907
commit 434dd70dd5

View File

@@ -22,3 +22,141 @@ more information on how to handle async states.
- [On Asynchronicity in Blaze](https://radekmie.dev/blog/on-asynchronicity-in-blaze/);
- [On Asynchronicity in Blaze (again)](https://radekmie.dev/blog/on-asynchronicity-in-blaze-again/);
Below you can check some examples of how to use async in Blaze, docs for this api are [here](https://www.blazejs.org/api/spacebars#Async-states)
## Simple example with states
::: code-group
```handlebars [profile.html]
{{#let name=getNameAsynchronously}}
{{#if @pending 'name'}}
We are fetching your name...
{{/if}}
{{#if @rejected 'name'}}
Sorry, an error occured!
{{/if}}
{{#if @resolved 'name'}}
Hi, {{name}}!
{{/if}}
{{/let}}
```
```js [profile.js]
Template.profile.helpers({
getNameAsynchronously() {
return Meteor.callAsync("getName");
}
});
```
:::
## Example with async lists
You can use let to handle async state while loading and iterating lists:
::: code-group
```handlebars [user_list.html]
{{#let users=getUsersAsync}}
{{#if @pending 'users'}}
We are fetching your list...
{{/if}}
{{#if @rejected 'users'}}
Sorry, an error occured!
{{/if}}
{{if @resolved 'users'}}
{{#each user in users}}
Hi {{user.name}}!
{{/each}}
{{/if}}
{{/let}}
```
```js [user_list.js]
Template.user_list.helpers({
getUsersAsync() {
return Meteor.callAsync("getUsers"); // returns a Promise<Array>
}
});
```
:::
If you just want to iterate and if there is nothing to show, you can use `else`:
::: code-group
```handlebars [profile.html]
{{#each user in getUsersAsync}}
{{user}}.
{{else}}
Pending, rejected, or resolved and empty.
{{/if}}
```
```js [profile.js]
Template.profile.helpers({
getUsersAsync() {
return Meteor.callAsync("getUsers"); // returns a Promise<Array>
}
});
```
:::
## Example with async `if` and `unless`
For handling with falsy or truthy values, you can use `if` and `unless`,
note that it will not render anything until it resolves the promise:
::: code-group
```handlebars [profile.html]
{{#if isOkAsync}}
Resolved and truthy.
{{else}}
Resolved and falsy.
{{/if}}
```
```js [profile.js]
Template.profile.helpers({
isOkAsync() {
return Meteor.callAsync("condition"); // returns a Promise<Boolean>
}
});
```
Same goes for `unless`:
::: code-group
```handlebars [profile.html]
{{#unless isOkAsync}}
Resolved and falsy.
{{else}}
Resolved and truthy.
{{/unless}}
```
```js [profile.js]
Template.profile.helpers({
isOkAsync() {
return Meteor.callAsync("condition"); // returns a Promise<Boolean>
}
});
```
:::