Skip to content

Instantly share code, notes, and snippets.

@mhuggins
Created September 15, 2017 21:05
Show Gist options
  • Save mhuggins/e3139eed0b22821f1aaa57995dc28a47 to your computer and use it in GitHub Desktop.
Save mhuggins/e3139eed0b22821f1aaa57995dc28a47 to your computer and use it in GitHub Desktop.
import _ from "lodash";
import { graphql } from "react-apollo";
import { compose, setDisplayName, wrapDisplayName } from "recompose";
const isServer = typeof window !== "object";
const DEFAULT_OPTIONS = {
fetchPolicy: isServer ? "network-first" : "cache-and-network"
};
function wrapOptions(baseOptions) {
return (...args) => {
const result = baseOptions(...args);
return { ...DEFAULT_OPTIONS, ...result };
};
}
function extendOptions(baseOptions) {
return { ...DEFAULT_OPTIONS, ...baseOptions };
}
const withGraphQuery = (query, baseConfig = {}) => (Component) => {
const baseOptions = baseConfig.options || {};
const options = _.isFunction(baseOptions) ? wrapOptions(baseOptions) : extendOptions(baseOptions);
const config = { ...baseConfig, options };
return compose(
graphql(query, config),
setDisplayName(wrapDisplayName(Component, "withGraphQuery"))
)(Component);
};
export default withGraphQuery;
@mhuggins
Copy link
Author

Higher-order React component that wraps graphql. I found this necessary to prevent the server-side for my isomorphic React app from caching responses while still allowing the client to fetch data from the network.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment