NextJS13中如何结合Apollo GraphQL的useSuspenseQuery使用fetchMore?
useSuspenseQuery调用fetchMore时出现404错误的解决方法
问题描述
- useSuspenseQuery作为实验性API,已按照useQuery文档规范实现,包含fetchMore等辅助方法
- 调用fetchMore时,无论是否配置updateQuery参数,均返回404错误
- 页面初始加载阶段,useSuspenseQuery能正常获取数据,可排除GraphQL接口URI本身错误的可能
期望目标
- 实现GraphQL的Relay风格游标分页功能
- 通过useSuspenseQuery提供的fetchMore方法加载更多分页数据
解决方案
问题根源在于环境变量仅在服务端生效,如果你的GraphQL接口地址是通过环境变量配置的,必须在next.config.js中显式声明该环境变量,才能让客户端代码正常访问到接口地址,否则fetchMore发起请求时会因找不到正确的URI而返回404。
同时修正了原代码中updateQuery的取值路径问题(确保从fetchMoreResult.postsConnection中获取数据,与初始查询的结构保持一致),以下是完整的组件代码:
const Blog = () => { const { loading, error, data, client, fetchMore } = useSuspenseQuery(postsQuery, { variables: { first: 3 }, fetchPolicy: "cache-and-network", }); const { edges, pageInfo } = data.postsConnection; return ( <Container> {<Posts posts={edges} />} <div> <button disabled={!pageInfo.hasNextPage} onClick={() => fetchMore({ variables: { first: 3, after: pageInfo.endCursor, }, updateQuery: (previousResult, { fetchMoreResult }) => { const newEdges = fetchMoreResult.postsConnection.edges; const newPageInfo = fetchMoreResult.postsConnection.pageInfo; return newEdges.length ? { postsConnection: { __typename: previousResult.postsConnection.__typename, edges: [...previousResult.postsConnection.edges, ...newEdges], pageInfo: newPageInfo, }, } : previousResult; }, }) } > Next </button> </div> </Container> ); };
内容的提问来源于stack exchange,提问作者Matheus Kroska
相关产品推荐
相关产品推荐

