Last active
April 10, 2017 19:45
-
-
Save jamesbirtles/16a3dfa79db719d2e96d29f37e9a5b45 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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