ApolloClient在分页操作时在mutation后自动refetch的解决方法
创始人
2024-09-09 08:00:44
0

在 Apollo Client 中,当进行分页操作时,经常会使用到 refetch 方法来重新拉取数据。但是,在进行了某些 mutation 操作后,需要在 refetch 时包含上一次的变化。这时,可以使用 update 方法来手动更新 Apollo cache,然后再触发 refetch。

示例代码:

import { useMutation } from '@apollo/client';
import { gql } from 'apollo-boost';

const MUTATION_CREATE_ITEM = gql`
  mutation CreateItem($name: String!, $priority: Int!) {
    createItem(input: { name: $name, priority: $priority }) {
      item {
        id
        name
        priority
      }
    }
  }
`;

const QUERY_GET_ITEMS = gql`
  query GetItems($cursor: ID) {
    items(first: 10, after: $cursor) {
      edges {
        node {
          id
          name
          priority
        }
      }
      pageInfo {
        hasNextPage
        endCursor
      }
    }
  }
`;

const ItemList = () => {
  const [createItem] = useMutation(MUTATION_CREATE_ITEM);
  const { data, loading, fetchMore, refetch } = useQuery(QUERY_GET_ITEMS);

  const handleSubmit = async (e) => {
    e.preventDefault();
    await createItem({
      variables: {
        name: e.target.elements.name.value,
        priority: parseInt(e.target.elements.priority.value, 10),
      },
      update: (cache, { data: { createItem } }) => {
        const { item } = createItem;
        const queryResult = cache.readQuery({
          query: QUERY_GET_ITEMS,
        });
        const { edges } = queryResult.items;
        const firstEdge = edges[0];

        // Add the new item to the Apollo cache
        cache.writeQuery({
          query: QUERY_GET_ITEMS,
          data: {
            items: {
              edges: [
                {
                  node: {
                    id: item.id,
                    name: item.name,
                    priority: item.priority,
                    __typename: 'ItemNode',
                  },
                  cursor: firstEdge.cursor - 1,
                  __typename: 'ItemNodeEdge',

相关内容

热门资讯

一分钟揭秘!手机游戏辅助脚本工... 一分钟揭秘!手机游戏辅助脚本工具,天天贵阳辅助插件,详细教程(有挂总结)所有人都在同一条线上,像星星...
热点推荐!温州茶苑破解版,情怀... 热点推荐!温州茶苑破解版,情怀莆仙到底是不是有挂,详细器(有挂解惑)1、这是跨平台的情怀莆仙到底是不...
我来教大家!福建天天开心辅助器... 我来教大家!福建天天开心辅助器是真的吗,天酷辅助器,详细app(有挂方针)1、超多福利:超高返利,海...
分享一款!点我休闲辅助器,大唐... 分享一款!点我休闲辅助器,大唐麻将开挂软件,详细工具(有挂攻略)1、超多福利:超高返利,海量正版游戏...
一分钟教你!微信小程序指尖四川... 一分钟教你!微信小程序指尖四川辅助器,多乐找刺激脚本,详细方法(有挂详细)1、超多福利:超高返利,海...
免费测试版!四川游戏家园通用辅... 免费测试版!四川游戏家园通用辅助,上品斗地主游戏辅助,详细app(有挂总结)该软件可以轻松地帮助玩家...
实测揭晓!798大菠萝辅助,边... 实测揭晓!798大菠萝辅助,边锋干瞪眼ios辅助,详细软件(有挂方略)边锋干瞪眼ios辅助能透视中分...
9分钟了解!多乐够级辅助软件,... 9分钟了解!多乐够级辅助软件,赣牌圈有挂吗,详细方法(有挂技巧)1、起透看视 多乐够级辅助软件辅助软...
技术分享!微信小程序辅助有哪些... 技术分享!微信小程序辅助有哪些,巴蜀长牌辅助,详细方法(有挂技术)1、微信小程序辅助有哪些公共底牌简...
一分钟快速了解!微信小程序游戏... 一分钟快速了解!微信小程序游戏破解微乐游戏,微乐小程序有脚本吗,详细工具(有挂工具)微信小程序游戏破...