Skip to content

Instantly share code, notes, and snippets.

@scurker
Created January 20, 2017 22:16
Show Gist options
  • Save scurker/b4cb9d9b5cc5662cf505ee233079b352 to your computer and use it in GitHub Desktop.
Save scurker/b4cb9d9b5cc5662cf505ee233079b352 to your computer and use it in GitHub Desktop.
Async Component in Preact
import { h, Component } from 'preact';
class AsyncComponent extends Component {
constructor() {
super();
this.state = { loading: true };
this.getAsyncState = this.getAsyncState.bind(this);
this.update = this.update.bind(this);
}
getAsyncState() {
let { promise, ...props } = this.props;
this.setState({ loading: true, error: null });
return promise(props);
}
update() {
this.getAsyncState()
.then(asyncState => this.setState({ loading: false, asyncState }))
.catch(error => this.setState({ loading: false, error }));
}
componentDidMount() {
this.update();
}
componentDidUpdate(prevProps) {
let queryRegex = /[?#]/;
if(this.props.url.split(queryRegex)[0] !== prevProps.url.split(queryRegex)[0]) {
this.update();
}
}
render({ Component, promise, ...props }, { asyncState, ...state }) {
return <Component { ...props } { ...asyncState } { ...state } />;
}
}
export default function withAsync(Component, promise) {
return function(props) {
return <AsyncComponent Component={Component} promise={promise} {...props} />;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment