Skip to content

Instantly share code, notes, and snippets.

@mosluce
Created January 23, 2019 04:57
Show Gist options
  • Save mosluce/96d788c4c6d60800f838dc3c2c805d82 to your computer and use it in GitHub Desktop.
Save mosluce/96d788c4c6d60800f838dc3c2c805d82 to your computer and use it in GitHub Desktop.
react-apollo Query hoc
import React from 'react';
import { Query } from "react-apollo";
import hoist from 'hoist-non-react-statics';
import compareProps from '../compareProps';
const withQuery = (query, { name, options = {}, mapPropKeys = [] }) => (WrappedComponent) => {
class WithQuery extends React.Component {
constructor() {
super();
this.state = {
retry: false,
};
}
shouldComponentUpdate(props, state) {
// 檢查指定的 key 是否有任何變動
return compareProps(this.props, props, Array.prototype.concat(mapPropKeys));
}
render() {
const {
retry,
} = this.state;
let opts = options;
if (typeof options === 'function') {
opts = options(this.props);
}
return (
<Query query={query} {...opts}>
{({ data, ...queryParams }) => {
const { error, loading, refetch, variables } = queryParams;
if ((loading || retry) && WrappedComponent.Loading) {
console.log('[lib]', 'withQuery', name, 'loading => ', loading, 'retry => ', retry);
return <WrappedComponent.Loading />;
}
if (error && WrappedComponent.Error) {
console.log('[lib]', 'withQuery', 'error', name, JSON.stringify(variables), error);
return <WrappedComponent.Error ctx={this} retry={refetch} />
}
console.log('[lib]', 'withQuery', 'data', name, data, JSON.stringify(variables), queryParams);
const props = {
...this.props,
[name]: {
...queryParams,
...data,
},
};
return <WrappedComponent {...props} />
}}
</Query>
);
}
}
return hoist(WithQuery, WrappedComponent, {});
}
export default withQuery;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment