1

This is for a list where items can reordered where the mutation input is the reordered array, and the mutation result is a list of photos in the new order after they have been saved to the database. The actual mutation works great, but I don't know what an optimisticResponse for an array is supposed to look like because it doesn't seem to happen.


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,
              },
            });
          },
        },
      }),
    }),
  }),
atkayla
  • 8,143
  • 17
  • 72
  • 132
  • The optimistic update should look exactly like the real result. So you're saying the real mutation result works fine, but not the optimistic version? – stubailo Nov 16 '16 at 05:17

1 Answers1

0

Thanks to @stubailo:

The optimistic update should exactly like the real result.

It turns out I was doing additional logic on the server that I didn't apply to the optimistic update. When I did, it worked:

  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,
              },
            });
          },
        },
      }),
    }),
  }),
atkayla
  • 8,143
  • 17
  • 72
  • 132