Created
November 13, 2017 18:51
-
-
Save iamdanthedev/67e12967a42571519bfbc59a8e870739 to your computer and use it in GitHub Desktop.
React composition with apollo query, mutation and react-router
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
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