Skip to content

Instantly share code, notes, and snippets.

@BenBrostoff
Last active January 10, 2019 20:13
Show Gist options
  • Save BenBrostoff/4e544db73630b6e488b58bca8272c930 to your computer and use it in GitHub Desktop.
Save BenBrostoff/4e544db73630b6e488b58bca8272c930 to your computer and use it in GitHub Desktop.
Apollo TypeScript example (GitHub API) - taken from Apollo docs
// The Result type we expect back.
// See https://developer.github.com/v3/repos/#get
interface Result {
repo: {
id: number;
name: string;
description: string;
html_url: string;
};
}
// The props we expect to be passed directly to this component.
interface OwnProps {
name: string;
}
// Credit https://codesandbox.io/s/github/apollographql/apollo-link-rest/tree/master/examples/typescript
// Define the Props for the Repo component using React Apollo's
// ChildProps generic inteface with the expected Result.
type Props = ChildProps<OwnProps, Result>;
// Standard React Component, using the injected data prop.
class RepoBase extends React.Component<Props, {}> {
public render() {
const data: ApolloQueryResult = this.props.data;
if (data && data.repo) {
return (
<div>
<h3>
<a href={data.repo.html_url}>{data.repo.name}</a>
</h3>
<p>{data.repo.description}</p>
</div>
);
} else if (data && data.loading) {
return <div>Loading...</div>;
} else {
return null;
}
}
}
const query = '...'; // removed for brevity
// Connect the component using React Apollo's higher order component
// and inject the data into the component. The Result type is what
// we expect the shape of the response to be and OwnProps is what we
// expect to be passed to this component.
const Repo = graphql<Result, OwnProps>(query, {
options: ({ name }) => ({ variables: { name } }),
})(RepoBase);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment