optimisticResponse对于数组结果是什么样的?

时间:2016-11-15 17:19:30

标签: graphql apollostack react-apollo

这是一个列表,其中项目可以重新排序,其中变异输入是重新排序的数组,并且变异结果是在新顺序中将照片保存到数据库后的列表。实际的突变效果很好,但我不知道数组的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,
              },
            });
          },
        },
      }),
    }),
  }),

1 个答案:

答案 0 :(得分: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,
              },
            });
          },
        },
      }),
    }),
  }),