Skip to content

Instantly share code, notes, and snippets.

@stubailo
Created February 11, 2017 17:27
Show Gist options
  • Save stubailo/e3c6131e9d03bcf1ad7827c1e229e687 to your computer and use it in GitHub Desktop.
Save stubailo/e3c6131e9d03bcf1ad7827c1e229e687 to your computer and use it in GitHub Desktop.
Using branch and renderComponent to display loading state with Recompose and React-Apollo
import React from 'react';
import { pure, branch, renderComponent, compose } from 'recompose';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import { Link } from 'react-router';
// Define a very basic loading state component - you could make this
// a nice animation or something
const Loading = () => (
<div>Loading</div>
);
// Define an HoC that displays the Loading component instead of the
// wrapped component when props.data.loading is true
const displayLoadingState = branch(
(props) => props.data.loading,
renderComponent(Loading),
);
// The pure component that renders UI
const BookSearchResultsPure = ({ data: { bookSearch } }) => (
<ul>
{bookSearch.map(book =>
<li key={book.id}>
<Link to={`/details/${book.id}`}>
{book.title} by {book.author.name}
</Link>
</li>
)}
</ul>
);
// The GraphQL query wrapper, provides a data prop with a loading
// field on it
const data = graphql(gql`
query BookSearchQuery($keyword: String!) {
...
}
`, {
options: ({ keyword }) => ({ variables: { keyword } }),
});
// Put everything together!
const BookSearchResults = compose(
data,
displayLoadingState,
pure,
)(BookSearchResultsPure);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment