Skip to content

Instantly share code, notes, and snippets.

@gtod
Created December 15, 2017 00:07
Show Gist options
  • Save gtod/9d86390d6d5f0a711ffd51c1628f62f5 to your computer and use it in GitHub Desktop.
Save gtod/9d86390d6d5f0a711ffd51c1628f62f5 to your computer and use it in GitHub Desktop.
import {Mutation, Query} from "./graphql/queries"
import {graphql, OptionProps} from "react-apollo"
import {FetchPolicy} from "apollo-client"
import {ComponentClass, StatelessComponent} from "react"
type Component<P> = ComponentClass<P> | StatelessComponent<P>
interface RenderProps<Props, QueryResult, QueryArgs> {
props: Props
data: QueryResult | null
loading: boolean
refetch: ((x: QueryArgs) => Promise<QueryResult>) | null
}
export function graphqlQuery<Props, QueryArgs, QueryResult>({
query,
variables,
fetchPolicy = "cache-first",
render,
skip = () => false,
}: {
query: Query<QueryArgs, QueryResult>;
variables: (x: Props) => QueryArgs;
fetchPolicy?: FetchPolicy;
skip?: (x: Props) => boolean;
render: Component<RenderProps<Props, QueryResult, QueryArgs>>;
}): ComponentClass<Props> {
return graphql<QueryResult, Props, RenderProps<Props, QueryResult, QueryArgs>>(query.document, {
props({ownProps, data}) {
return {
props: ownProps,
data: data || null,
loading: !data || data.loading,
refetch: data && data.refetch ? (x: QueryArgs) => data.refetch(x).then : null,
}
},
options(props) {
return {
variables: variables(props),
fetchPolicy,
}
},
skip,
})(render)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment