如何使用支持分页的 fetch api 从反应中编写 graphQL 查询?

How to write graphQL query from react using fetch api which support pagination?

信息:

我可以执行的任务:

想要执行以下操作:

通过查看各种文档、博客和我当前的要求来解决:

const Post = (props) => {
  const [isLoading, setLoading] = useState(true);
  const [posts, setPosts] = useState([])
  const [offset, setOffset] = useState(0)
  const [hasPrev, setHasPrev] = useState(false)
  const [hasNext, setHasNext] = useState(false)
  const pageSize = 10

  useEffect(() => {
    const loadData = () => {
      setLoading(true)
      const requestOptions = getGraphqlRequestOptions(pageSize, offset)
      fetch(graphql_url, requestOptions)
        .then(response => {
          setLoading(false)
          return response.json()
        })
        .then(data => {
          setHasNext(data.data.allPosts.pageInfo.hasNextPage)
          setPosts(data.data.allPosts.edges)
          setHasPrev(offset !== 0)
        })
    }
    loadData()
  }, [offset]);

  const handleNextClick = () => {
    setOffset(offset + pageSize)
  };
  const handlePrevClick = () => {
    setOffset(offset - pageSize)
  };
  useEffect(()=> {
    document.title = "MyTitle"
    setOffset(0)
  }, []);

  return (
    <>
      ... code to display table
      <div className="row mb-5">
        <Button 
          variant="outline-primary"
          className="col-1 me-auto"
          disabled={!(hasPrev || isLoading)}
          size="sm" block
          onClick={!isLoading ? handlePrevClick : null}
        >
          {isLoading ?  'Loading...' : 'Previous'}
        </Button>
        <Button 
          className="col-1 ms-auto"
          disabled={!(hasNext || isLoading)}
          onClick={!isLoading ? handleNextClick: null}
          variant="outline-primary" size="sm" block
        >
          {isLoading ?  'Loading...' : 'Next'}
        </Button>
      </div>
    </>
  }

我被卡住了,因为有很多选择,但没有具体的例子来实现它。
例如:

  • 我们可以使用:
    1. query{allPosts(first:10, after:"last cursor"){pageInfo{hasPrevPage hasNextPage startCursor endCursor} edge{node{...}}}
    2. query{allPosts(first:10, offset:0){}} // currently used
    3. `查询{allPosts(first:10,之前:'start cursor'
    4. 以上所有查询都使用 last:10 而不是 first:10,等等
  • 除此之外,它 returns 一个具有 hasNextPage, hasPrevPage, startCursor, endCursor 的 PageInfo 对象。
    • 它提供的信息难以理解
    • 使用查询 (1),即使用 firstafter 选项,hasPrevPage 总是 false
    • 使用 query(3) 即使用 before 选项,hasNextPage 总是 false
    • 因此需要跟踪下一页和上一页是否存在是困难的。