Last active
August 26, 2021 15:24
-
-
Save nathansmith/7ab8573fcb69c52c078ca38227697024 to your computer and use it in GitHub Desktop.
Example of Apollo's declarative "query" and "mutation" syntax.
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
// Dependencies. | |
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { Mutation, Query } from 'react-apollo'; | |
// Mutations and queries. | |
import MY_MUTATION from './MY_MUTATION.graphql'; | |
import MY_QUERY from './MY_QUERY.graphql'; | |
// UI components. | |
import DumbComponent from './DumbComponent'; | |
// Define HOC. | |
const HigherOrderComponent = ({ | |
// Props. | |
customerId = '', | |
}) => { | |
// Query info. | |
const queryInfo = { | |
query: MY_QUERY, | |
variables: { customerId }, | |
}; | |
// Mutation info. | |
const mutationInfo = { | |
mutation: MY_MUTATION, | |
}; | |
// Expose query. | |
return ( | |
<Query {...queryInfo}> | |
{({ loading, error, data }) => { | |
// Expose mutation. | |
return ( | |
<Mutation {...mutationInfo}> | |
{(mutationMethod) => { | |
// Still loading? | |
if (loading) { | |
// Early exit. | |
return ( | |
<p> | |
Loading… | |
</p> | |
); | |
// Error exists? | |
} else if (error) { | |
// Early exit. | |
return ( | |
<p> | |
Error: {error.message} | |
</p> | |
); | |
} | |
// Peel apart data. | |
const { whatever } = (data || {}); | |
// Component info. | |
const componentInfo = { | |
customerId, | |
whatever, | |
handleSubmit: (variables) => { | |
mutationMethod({ variables }); | |
}, | |
}; | |
// Expose UI. | |
return ( | |
<DumbComponent | |
{...componentInfo} | |
/> | |
); | |
}} | |
</Mutation> | |
); | |
}} | |
</Query> | |
); | |
}; | |
// Validation. | |
HigherOrderComponent.propTypes = { | |
customerId: PropTypes.string.isRequired, | |
}; | |
// Export. | |
export default HigherOrderComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment