Skip to content

Instantly share code, notes, and snippets.

@nelix
Forked from threepointone/async-disto.js
Created March 22, 2016 10:16
Show Gist options
  • Save nelix/3c234371e42d6f71b4a8 to your computer and use it in GitHub Desktop.
Save nelix/3c234371e42d6f71b4a8 to your computer and use it in GitHub Desktop.
async action creators in disto
/* global fetch*/
import {Dis, act} from 'disto';
let {dispatch, register} = new Dis();
function timeout(t){
return new Promise(resolve =>
setTimeout(()=> resolve(true), t));
}
// setup the search action creator
const $ = act(dispatch, {
search: async function(query){
// wait for 100 ms before fetching
await timeout(100);
return fetch(`/search/${query}`);
// alternately, you could return a promise from a regular function
}
});
const store = register({
query: '',
loading: false,
results: [],
err: null
}, (o, action, ...args) => {
switch(action){
// search begins
case $.search:
let [query] = args;
return { ...o,
query,
loading: true,
err: null
};
// response comes back
// .done is magically created
case $.search.done:
let [err, results] = args; // node.js style arguments
return { ...o,
loading: false,
err,
results
};
default: return o;
}
});
// listen to all 'changes'
store.subscribe(o => console.log('change', o));
// in real life you'd connect this to a react component via .observe() or similar
// fire off a couple of requests
$.search('red shoes');
$.search('blue jeans');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment