Skip to content

Instantly share code, notes, and snippets.

@mjoslyn
Created June 19, 2018 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjoslyn/4a50056f20d0afb127224b2cd36cbccf to your computer and use it in GitHub Desktop.
Save mjoslyn/4a50056f20d0afb127224b2cd36cbccf to your computer and use it in GitHub Desktop.
//@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>;
}
}
}
@mjoslyn
Copy link
Author

mjoslyn commented Jul 15, 2018

Use like this

<PrismicLoader
          url={url}
          query={api =>
            api.query(Prismic.Predicates.at("document.type", "homepage"))
          }
          callback={res => {
            return res.results[0].data;
          }}
          renderError={() => <Error />}
          renderLoading={() => <BlankLoader />}
          renderLoaded={({ response }) => (
                <h1>{response.title}/h1>
          )}
/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment