Skip to content

Instantly share code, notes, and snippets.

@mdvanes
Last active May 5, 2019 18:27
Show Gist options
  • Save mdvanes/ef6036398556f8747d32e748408d4a4a to your computer and use it in GitHub Desktop.
Save mdvanes/ef6036398556f8747d32e748408d4a4a to your computer and use it in GitHub Desktop.
What are best practices to deal with multiple Apollo GraphQL queries?
import React from 'react';
import { compose } from 'react-apollo';
import { graphql, gql } from 'apollo-boost';
/* Let's assume Authors and Books are retrieved with separate queries, resulting in 2 HOCs */
const withAuthorsQuery = graphql(gql`... some query...`, { name: 'authorsQuery' });
const withBooksQuery = graphql(gql`... some other query...`, { name: 'booksQuery' });
/* Now we want to use a third party component needs books and authors */
const ThirdPartyComponent = ({ books, authors }) => (<div>books: {books} authors: {authors}</div>);
/* But I only want to load the ThirdPartyComponent if both books and authors are available,
neither has errors and neither is loading */
const MyComponent = ({ booksQuery, authorsQuery }) => {
/*
Now I have 2 issues:
1. I can't use destructuring anymore, since both Authors and Books have a loading and an error prop;
2. Now I have to explicitely check the loading/error state of each query. I realize I could make a helper function that takes queries and returns an overall state (see below), but I am interested to see how other develoepr deal with multiple queries.
Is there a best practice to deal with composing multipe queries?
*/
if (booksQuery.loading || authorsQuery.loading) {
return <p>Loading</p>;
}
if (booksQuery.error || authorsQuery.error) {
return <p>Loading</p>;
}
if (booksQuery.books && authorsQuery.authors) {
return <ThirdPartyComponent books={booksQuery.books} authors={authorsQuery.authors} />;
}
return <div />;
};
/* Example of the helper */
const multiQueryHelper = queries => ({
loading: queries.some(q => q.loading),
error: queries.some(q => q.error),
});
const EnhancedMyComponent = compose(
withAuthorsQuery,
withBooksQuery,
)(MyComponent);
export default EnhancedMyComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment