Реагируйте на бесконечный свиток с GraphQL - PullRequest
0 голосов
/ 14 января 2020

Я пытаюсь подключить свою страницу, чтобы заполнить больше элементов с помощью graphql при прокрутке с использованием бесконечной прокрутки. сейчас я сталкиваюсь с проблемой обновления страницы при каждой прокрутке, а затем с ошибкой при достижении максимального значения hasMore. если у кого-то есть идеи о том, как заставить это работать, это будет ОГРОМНАЯ помощь. я использую следующий js, машинопись, graphql и reactjs бесконечный свиток

import React, { useState } from 'react';
import gql from 'graphql-tag';
import InfiniteScroll from 'react-infinite-scroller';
import { useQuery } from '@apollo/react-hooks';
import { useRouter } from 'next/router';
import { withApollo } from '../../lib/apollo';

import { ErrorIndicator, LoadingIndicator, SubHeading } from '../../components/Atoms/';
import { Card, SubNav } from '../../components/Molecules/';
import { ArticleList, SixCards } from '../../components/Organisms/';
import { BREAKPOINT } from '../../constants/';
import { countryData } from '../../data/countryData';

export const queryCreator = (categories, count): any => gql`
{
  articles(lang: "en", categories: ["${categories}"], count: ${count}){
    id
    slug
    title
    content
    featuredImage
    creator {
      name
      id
    }
    categories {
      name
      id
    }
  }
}
`;

export const News: React.FC = () => {
  const [articleListState, updateArticleList] = useState({
    count: 8,
    articleList: []
  });

  const { count, articleList } = articleListState;
  const router = useRouter();
  const { categories } = router.query;
  const categoriesToQuery = categories ? categories.toString() : '';
  const formattedQuery = queryCreator(categoriesToQuery, count);
  const { loading, error, data } = useQuery(formattedQuery);

  if (error) {
    return <ErrorIndicator />;
  }

  if (loading) {
    return <LoadingIndicator />;
  }
  const { articles } = data;

  // updateArticleList({ count: 8, articleList: articles });

  const hasMore = () => count <= 13;
  const loadMore = () => {
    if (hasMore) {
      const addOne = count + 1;
      updateArticleList({ count: addOne, articleList: articles });
    }
  };

  const items = [];

  articleList.map((article) =>
    items.push(
      article && (
        <div className="article" key={article.id}>
          <Card key={article.id} article={article} size="short" />
          <style jsx>{`
            .article {
              padding: 6px 0;
              margin: 0 auto;
            }
          `}</style>
        </div>
      )
    )
  );
  console.log(items, count);
  return (
    <main className="articles-container">
      <SubNav />
      <SixCards articles={articles} />
      <div className="article-list">
        <InfiniteScroll
          pageStart={0}
          loadMore={loadMore}
          hasMore={hasMore()}
          loader={
            <div key={0}>
              <SubHeading title="Loading . . ." Tag="h5" />
            </div>
          }
        >
          {items}
          {/* <ArticleList articles={articleList} /> */}
        </InfiniteScroll>
      </div>
      <style jsx>{`
        main.articles-container {
          min-height: 80vh;
          display: flex;
          flex-direction: column;
          width: 80%;
          margin: 0 auto;
        }

        .article-list {
          display: flex;
          flex-direction: column;
          justify-content: center;
          // width: 100%;
          max-width: 1020px;
          margin: 10px auto;
          align-self: center;
        }

        @media only screen and (max-width: ${BREAKPOINT}px) {
          main.articles-container {
            width: 90%;
          }
        }
      `}</style>
    </main>
  );
};

export default withApollo(News);

...