Skip to content

Instantly share code, notes, and snippets.

@iamdanthedev
Created November 13, 2017 18:51
Show Gist options
  • Save iamdanthedev/67e12967a42571519bfbc59a8e870739 to your computer and use it in GitHub Desktop.
Save iamdanthedev/67e12967a42571519bfbc59a8e870739 to your computer and use it in GitHub Desktop.
React composition with apollo query, mutation and react-router
import { graphql, QueryProps } from 'react-apollo';
/**
* QUERY
*/
const PAYMENT_QUERY = gql`
query payment($id: ID!) {
payment(id: $id) {
id
amount
}
}
`;
// some mutation..
const MUTATE = gql`mutation updatePayment {}`;
// ideally these all have to be generated with graphql-code-gen and simply imported in
// so you don't have to keep describing your query in two places
type PaymentQuery = { payment: Payment; }
type PaymentMutation = { updatePayment: { /* some return fields */ } }
type PaymentMutationVars = { /* your vars */ }
/**
* CONTAINER
*/
interface OwnProps {
paymentid: string;
onPaymentLoaded: (payment: Payment) => void;
}
type Data = { data: PaymentQuery & QueryProps };
type Mutation = { mutate: MutationFunc<PaymentMutation, PaymentMutationVars> };
type WrappedProps = OwnProps
& Data
& Mutation
& RouteComponentProps<{}>; // this describes withRouter (for example)
// plus any other composed types
export const Payment = compose<WrappedProps, OwnProps>(
// react-router for example..
withRouter,
graphql<PaymentQuery, OwnProps>(PAYMENT_QUERY, {
options: ({ paymentid }) => ({
variables: { id: paymentid }
}),
props: ({ data, ownProps }) => ({ ...data, ownProps })
}),
graphql(MUTATE),
// this will show loader and error components when needed
// so you don't have to check for data.error and data.loading in every single container
// see https://gist.github.com/rasdaniil/36c94276cbfa6247f111fbc0fcc68f37
dataLoadingOrError(),
)(props => {
const { payment, onPaymentLoaded } = props;
// if you need router here
// const { history } = props;
// history.push('/');
// mutation example:
// props.mutate(/* you vars */)
return (
<PaymentView
loading={loading}
error={error}
payment={payment}
onPaymentLoaded={onPaymentLoaded}
/>
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment