Skip to content

Instantly share code, notes, and snippets.

@ericdfields
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ericdfields/c798d1f45f04e41614b3 to your computer and use it in GitHub Desktop.
Save ericdfields/c798d1f45f04e41614b3 to your computer and use it in GitHub Desktop.
Resolving local UI state with Flux using Flummox and Promises
import Flux from 'path/to/flux.js'
window.MyApp.flux = new Flux()
import { Actions, Store, Flummox } from 'flummox';
export default class Flux extends Flummox {
constructor() {
super();
this.createActions('Widgets', require('path/to/widget_actions'));
this.createActions('Widgets', require('path/to/widget_store'), this);
}
}
var React = require('react')
module.exports = React.createClass({
// reactStuff
handleCreate: function(widget_data) {
//
// … but we can also use the response in the widget to do something afterward ("then")
//
MyApp.flux.getActions('Widgets').createWidget(widget_data).then(this.handleCreateResponse)
},
handleCreateResponse: function(response) {
// response.data is also available
if (response.status == 'success') {
this.closeThisComponent()
} else {
// do smething on fail
}
}
})
import { Actions } from 'flummox';
var $ = require('jquery') // or some other ajax lib resource
export default class WidgetActions extends Actions {
//
// inspired by https://reactiflux.slack.com/archives/flummox/p1432075752001274
// Using an async will dispatch the response to the store…
//
async createWidget(widget_data) {
let response;
await $.post('/api/widgets',widget_data).done((data,status) => {
response = { data, status }
})
return await response
}
}
import { Store } from 'flummox';
export default class WidgetStore extends Store {
constructor(flux) {
super(); // Don't forget this step
const actions = flux.getActions('Widgets');
this.register(actions.createWidget, this.handleCreate);
this.state = {};
}
handleCreate(widget_data) {
// do something w/ your new widget delivered from the server via the action promise
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment