Created
January 20, 2017 22:16
-
-
Save scurker/b4cb9d9b5cc5662cf505ee233079b352 to your computer and use it in GitHub Desktop.
Async Component in Preact
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 { 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