【问题标题】:Apollo GraphQL FetchMoreApollo GraphQL Fetch更多
【发布时间】:2020-10-13 14:16:04
【问题描述】:

我正在尝试让 Apollo gql 在单击按钮后加载更多帖子。所以它会加载接下来的 15 个结果,每次点击 - 加载更多。

这是我当前的代码

import Layout from "./Layout";
import Post from "./Post";
import client from "./ApolloClient";
import { useQuery } from "@apollo/react-hooks"
import gql from "graphql-tag";

const POSTS_QUERY = gql`
  query {
    posts(first: 15) {
      nodes {
        title
        slug
        postId
        featuredImage {
          sourceUrl
        }
      }
    }
  }
`;

const Posts = props => {
  let currPage = 0;
  const { posts } = props;
  const { loading, error, data, fetchMore } = useQuery(
    POSTS_QUERY,
    {
      variables: {
        offset: 0,
        limit: 15
      },
      fetchPolicy: "cache-and-network"
    });

  function onLoadMore() {
    fetchMore({
      variables: {
        offset: data.posts.length
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev;
        return Object.assign({}, prev, {
          posts: [...prev.posts, ...fetchMoreResult.posts]
        });
      }
    });
  }

  if (loading) return (
      <div className="container mx-auto py-6">
        <div className="flex flex-wrap">
          Loading...
        </div>
      </div>
  );
  if (error) return (
      <div className="container mx-auto py-6">
        <div className="flex flex-wrap">
          Oops, there was an error :( Please try again later.
        </div>
      </div>
  );
  return (
      <div className="container mx-auto py-6">
        <div className="flex flex-wrap">
          {data.posts.nodes.length
            ? data.posts.nodes.map(post => <Post key={post.postId} post={post} />)
            : ""}
        </div>

        <button onClick={() => { onLoadMore() }}>Load More</button>
      </div>
  );
};

export default Posts;

当您单击加载更多时,它会刷新查询和控制台错误 Invalid attempt to spread non-iterable instance

我一直在加载解决方案,但很多示例都是上一页或下一页,如传统分页。或者我不想要的基于游标的无限加载器。我只想在 onClick 列表中添加更多帖子。

感谢任何建议,谢谢。

【问题讨论】:

    标签: apollo react-apollo


    【解决方案1】:

    你当前的POSTS_QUERY 不接受变量,所以首先你需要改变这个:

    const POSTS_QUERY = gql`
      query postQuery($first: Int!, $offset: Int!) {
        posts(first: $first, offset: $offset) {
          nodes {
            title
            slug
            postId
            featuredImage {
              sourceUrl
            }
          }
        }
      }
    `;
    

    现在,它将使用您的useQueryfetchMore 中列出的变量。

    要完成错误是因为updateQuery不正确,请将其更改为:

    function onLoadMore() {
        fetchMore({
          variables: {
            offset: data.posts.nodes.length
          },
          updateQuery: (prev, { fetchMoreResult }) => {
            if (!fetchMoreResult) return prev;
            return { posts: { nodes: [...prev.posts.nodes, ...fetchMoreResult.posts.nodes] } };
            });
          }
        });
      }
    

    【讨论】:

      【解决方案2】:

      我建议使用 useState 挂钩来管理存储数据集中当前偏移量的变量,放置一个 useEffect 来观察该偏移量的变化,将偏移值作为查询变量传递以加载数据。去掉 fetchmore,useEffect 钩子就可以了。

      当用户点击加载更多按钮时,你只需要更新偏移值,就会触发查询和更新数据。

      const [offset,setOffset] = React.useState(0)
      const [results, setResults] = React.useState([])
      
      const { loading, error, data } = useQuery(
          POSTS_QUERY,
          {
            variables: {
              offset: offset,
              limit: 15
            },
            fetchPolicy: "cache-and-network"
          }
      );
      
      React.useEffect(() => {
       const newResults = [...results, ...data]
       setResults(newResults)
      }, [data])
      
      function onLoadMore() {
       setOffset(results.data.length)
      }
      

      【讨论】:

      • 那不需要我一开始就查询所有帖子吗?
      • 查询变量'offset'将是一个状态变量,每当它被更新时,查询将运行并且返回的数据在另一个状态变量的set中。这涵盖了 fetchMore 功能的功能。最初无需查询所有内容。仅要求 15 个结果并在加载更多时更新偏移量(来自状态)。
      • 你能帮忙举个例子吗,对不起,我想不通:(
      • 感谢您的帮助,不幸的是,我收到“传播不可迭代实例的无效尝试”
      • API返回的数据好像是不可迭代的。将其转储到控制台并检查,它会有所帮助:)
      猜你喜欢
      • 2019-07-26
      • 1970-01-01
      • 2020-10-20
      • 2019-11-27
      • 1970-01-01
      • 2019-11-10
      • 2018-03-20
      • 2021-03-03
      • 2017-08-13
      相关资源
      最近更新 更多