Created
February 11, 2017 17:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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