Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of Apollo's declarative "query" and "mutation" syntax.
// 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'
import MY_QUERY from './my_query'
// UI components.
import DumbComponent from './dumb_component'
// Define HOC.
const HigherOrderComponent = (props = {}) => {
// Props.
const {customerId} = props
// 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
You can’t perform that action at this time.