Created
June 19, 2018 20:33
-
-
Save mjoslyn/4a50056f20d0afb127224b2cd36cbccf 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
//@flow | |
import React from "react"; | |
import PrismicIO from "prismic-javascript"; | |
import type { APIOptions, Response } from "prismic-javascript"; | |
type Props = { | |
url: string, | |
apiOptions: APIOptions, | |
query: any, | |
callback: any => any, | |
queryKey: string, | |
predicates: Predicates, | |
predicateOptions: Options, | |
children: any | |
}; | |
type State = { | |
loading: boolean, | |
error: boolean | Error, | |
response: Response | |
}; | |
export default class PrismicLoader extends React.Component { | |
props: Props; | |
state: State; | |
static defaultProps = { | |
url: "", | |
apiOptions: {}, | |
renderLoading: () => null, | |
renderLoaded: () => null, | |
renderError: () => null, | |
query: () => null, | |
callback: res => res | |
}; | |
constructor(props: Props) { | |
super(props); | |
this.state = { | |
loading: true, | |
error: null, | |
response: {} | |
}; | |
} | |
componentDidMount = () => { | |
const { url, apiOptions, query, callback } = this.props; | |
PrismicIO.api(url, apiOptions) | |
.then((api: API) => query(api)) | |
.then((response: Response) => { | |
this.setState((state: State) => ({ | |
...state, | |
loading: false, | |
response: callback(response) | |
})); | |
}) | |
.catch((err: Error) => { | |
this.setState((state: State) => ({ | |
...state, | |
loading: false, | |
error: err | |
})); | |
}); | |
}; | |
render() { | |
const prismic = { | |
loading: this.state.loading, | |
error: this.state.error, | |
response: this.state.response | |
}; | |
if (this.state.loading) { | |
return <div>{this.props.renderLoading(prismic)}</div>; | |
} | |
if (this.state.error) { | |
return <div>{this.props.renderError(prismic)}</div>; | |
} | |
if (!this.state.loading) { | |
return <div>{this.props.renderLoaded(prismic)}</div>; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use like this