Skip to content

Instantly share code, notes, and snippets.

@neborn
Last active February 14, 2021 01:36
Show Gist options
  • Save neborn/de9bf2df1f55dac9fed8c033ce8f7c78 to your computer and use it in GitHub Desktop.
Save neborn/de9bf2df1f55dac9fed8c033ce8f7c78 to your computer and use it in GitHub Desktop.
Passing Simple Action Arguments
import Component from '@glimmer/component';
import { action, computed } from '@ember/object';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';
export default class ContainerComponent extends Component {
@service
api;
// this should be much cleaner with ember-concurrency 2.0
@computed('asyncActionTask.last.{isRunning,isSuccessful,isError}')
get taskProxy() {
const {
isError,
isRunning,
isSuccessful
} = this.asyncActionTask?.last ?? {};
return {
isError,
isRunning,
isSuccessful
};
}
@action
performAsyncAction(willSucceed) {
this.asyncActionTask.perform(willSucceed);
}
@(task(function * (willSucceed) {
// This funciton would likely include additional request and response decoration logic, along with possibly its own side effects.
yield this.api.makeCall(willSucceed);
}).drop())
asyncActionTask;
}
import Service from '@ember/service';
import { action } from '@ember/object';
const TIMEOUT = 1000;
export default class ApiService extends Service {
@action
makeCall(willSucceed) {
return new Promise((resolve, reject) => {
const callback = willSucceed ?
() => resolve([true, 200]) :
() => reject([false, 500]);
setTimeout(callback, TIMEOUT);
});
}
}
<Presentation
@requestState={{this.taskProxy}}
@onClick={{this.performAsyncAction}} />
{{#if @requestState.isSuccessful}}
<p>It worked!</p>
{{/if}}
{{#if @requestState.isError}}
<p>You should be able to see an error in the console.</p>
{{/if}}
<button
type="button"
disabled={{@requestState.isRunning}}
{{on "click" (fn @onClick true)}}
>
Perform async action resolve
</button>
<button
type="button"
disabled={{@requestState.isRunning}}
{{on "click" (fn @onClick false)}}
>
Perform async action reject
</button>
{
"version": "0.17.1",
"EmberENV": {
"FEATURES": {},
"_TEMPLATE_ONLY_GLIMMER_COMPONENTS": false,
"_APPLICATION_TEMPLATE_WRAPPER": true,
"_JQUERY_INTEGRATION": true
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js",
"ember": "3.18.1",
"ember-template-compiler": "3.18.1",
"ember-testing": "3.18.1"
},
"addons": {
"@glimmer/component": "1.0.0",
"ember-concurrency": "1.3.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment