Skip to content

Instantly share code, notes, and snippets.

@jamesbirtles
Last active April 10, 2017 19:45
Show Gist options
  • Save jamesbirtles/16a3dfa79db719d2e96d29f37e9a5b45 to your computer and use it in GitHub Desktop.
Save jamesbirtles/16a3dfa79db719d2e96d29f37e9a5b45 to your computer and use it in GitHub Desktop.
import { Component } from 'preact';
type Deferred<T> = {
[P in keyof T]?: Promise<T[P]>;
};
function isPromise<T>(V: any): V is Promise<T> {
return 'then' in V;
}
export function asyncState<S>(component: Component<any, S>, state: Deferred<S>) {
// TODO: add observable support
Object.keys(state)
.forEach((key: keyof S) => {
const value = state[key];
if (isPromise<any>(value)) {
value.then(res => component.setState(<any> { [key]: res }))
} else {
throw new Error('Unknown type passed to bindState');
}
})
}
import { asyncState } from './asyncState';
class Posts extends Component<any, any> {
public componentDidMount() {
asyncState(this, { posts: fetch('/api/posts').then(res => res.json()) })
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment