Created
May 8, 2017 21:27
-
-
Save scurker/fd4a1cf79737b527f313bf011a702e03 to your computer and use it in GitHub Desktop.
An async higher order component that resolves a promise via props
This file contains hidden or 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 })); | |
} | |
componentWillMount() { | |
let { initialState } = this.context; | |
if(initialState) { | |
this.state = { ...initialState }; | |
} | |
} | |
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