1

这是一个列表,其中项目可以重新排序,其中变异输入是重新排序的数组,变异结果是保存到数据库后按新顺序排列的照片列表。实际的突变效果很好,但我不知道optimisticResponse数组应该是什么样的,因为它似乎没有发生。


input InputItemOrder {
  key: String
  order: Int
  ref: InputPhoto
}

input InputPhoto {
  public_id: String
  secure_url: String
}

type Mutation {
  orderMyPhotos(itemOrder: [InputItemOrder]): [Photo]
}

type Photo {
  public_id: String
  secure_url: String
  order: Int
}

const ORDER_MY_PHOTOS_MUTATION = gql`
mutation OrderMyPhotos($itemOrder: [InputItemOrder]) {
  orderMyPhotos(itemOrder: $itemOrder) {
    public_id
    secure_url
    order
  }
}
`;

  graphql(ORDER_MY_PHOTOS_MUTATION, {
    props: ({ ownProps, mutate }) => ({
      order: (itemOrder) => mutate({
        variables: { itemOrder },
        optimisticResponse: {
          __typename: 'Mutation',
          orderMyPhotos: itemOrder.map(i => ({
            __typename: 'Photo',
            public_id: i.ref.public_id,
            secure_url: i.ref.secure_url,
            order: i.order,
          })),
        },
        updateQueries: {
          MyPhotos: (prev, { mutationResult }) => {
            const orderedPhotos = mutationResult.data.orderMyPhotos;
            return update(prev, {
              userPhotos: {
                $set: orderedPhotos,
              },
            });
          },
        },
      }),
    }),
  }),
4

1 回答 1

0

感谢@stubailo:

乐观的更新应该和真实的结果完全一样。

事实证明,我在服务器上执行了未应用于乐观更新的附加逻辑。当我这样做时,它起作用了:

  graphql(ORDER_MY_PHOTOS_MUTATION, {
    props: ({ ownProps, mutate }) => ({
      order: (itemOrder) => mutate({
        variables: { itemOrder },
          optimisticResponse: {
            __typename: 'Mutation',
            orderMyPhotos: _.sortBy(itemOrder.filter(i => _.isNumber(i.order)).map(j => ({
              __typename: 'Photo',
              order: j.order,
              public_id: j.ref.public_id,
              secure_url: j.ref.secure_url,
            })), 'order')
          },
        updateQueries: {
          MyPhotos: (prev, { mutationResult }) => {
            return update(prev, {
              userPhotos: {
                $set: mutationResult.data.orderMyPhotos,
              },
            });
          },
        },
      }),
    }),
  }),
于 2016-11-16T06:40:14.823 回答