Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active August 26, 2021 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansmith/7ab8573fcb69c52c078ca38227697024 to your computer and use it in GitHub Desktop.
Save nathansmith/7ab8573fcb69c52c078ca38227697024 to your computer and use it in GitHub Desktop.
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.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