cezarneaga
6/17/2017 - 12:49 AM

example-fetch-more-react-apollo.js

import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import { gql } from 'graphql-tools';

const QUERY = gql`
  query MatchesByDate($date: Int) {
    matches(date: $date) {
      id
      minute
      period
      highlights {
        ...
      }
      ...
    }
  }
`;

class MatchList extends Component {      
  render() {
    const ({ data: { loading, errors, matches } }) = this.props;

    return (
      <div className="matchlist">
        {loading && <div className="loader" />}
        {errors && <div className="errors">...</div>}

        {!loading && !matches && <span className="none">No Matches Found!</span>}

        {!loading &&
          matches &&
          matches.map(match => <div className="match">...</div>)}

        {!loading &&
          matches &&
          <button onClick={this.onFetchMore}> 
            Fetch More Matches
          </button>}
      </div>
    );
  }
  
  onFetchMore = () => {
    const ({ data: { matches, fetchMore } }) = this.props;

    fetchMore({
      variables: { date: matches[matches.length - 1].date },
      updateQuery: (previousResult, { fetchMoreResult, queryVariables }) => {
        return {
          ...previousResult,
          // Add the new matches data to the end of the old matches data.
          matches: [
            ...previousResult.matches,
            ...fetchMoreResult.matches,
          ],
        };
      },
    });
  }
}

export default graphql(QUERY)(MatchList);