Skip to content

Instantly share code, notes, and snippets.

@renganatha10
Created November 21, 2018 18:14
Show Gist options
  • Save renganatha10/d314a549ba21cba06e4026893153ed78 to your computer and use it in GitHub Desktop.
Save renganatha10/d314a549ba21cba06e4026893153ed78 to your computer and use it in GitHub Desktop.
Common GraphQL HOC to handle Common Error and Loading state and its component
import React from 'react';
import { graphql, compose } from 'react-apollo';
// Common Loading Component
import LoadingComponent from './../components/Loader';
// Common Error Component
import ErrorComponent from './../components/ErrorComponent';
const withCommonQueries = ({ queries }) => SuccessComponent => {
const CommonQueryComponent = props => {
try {
if (queries.length === 1) {
const {
data: { loading, error },
} = props;
if (loading) return <LoadingComponent />;
else if (error) return <ErrorComponent />;
return <SuccessComponent {...props.data} />;
} else {
const propNames = queries.map(({ name }) => name).map(key => props[key]);
const loading = propNames.some(item => item.loading);
const error = propNames.some(item => item.error);
if (loading) return <LoadingComponent />;
else if (error) return <ErrorComponent />;
return <SuccessComponent {...props} />;
}
} catch (err) {
//eslint-disable-next-line
console.log(err, 'Error on QueryCOmponent');
return <ErrorComponent msg="Specify Name for all the Quries" />;
}
};
return class EnhancedCommonComponent extends React.PureComponent {
render() {
const graphqlQuries = [];
queries.forEach(({ query, options, name }) => {
let queryOptions = options;
if (typeof options === 'function') {
queryOptions = options(this.props);
}
graphqlQuries.push(graphql(query, { name, options: queryOptions, errorPolicy: 'all' }));
});
const Query = compose(...graphqlQuries)(CommonQueryComponent);
return <Query />;
}
};
};
export default withCommonQueries;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment