0

I'm fetching a query, and modifying the order of the list in it, using cache.modify on the drag end. This does modify cache, as it should but, it takes milliseconds to do that.

How to reproduce the issue: I'm using react beautiful dnd, to make drag-n-drop card. It provides onDragEnd handler, where we can specify what happens when the user stops dragging. In this case, I want to reorder the list on the drag end.

Cache modify:

  cache.modify({
    id: cache.identify(data.pod),
    fields: {
      stories(existingStoriesRefs, { readField }) {
        return reorder(existingStoriesRefs, sourceIndex, destinationIndex);
      },
    },
  });

Reorder logic:

  const reorder = (list: any[], startIndex: number, endIndex: number) => {
    const result = Array.from(list);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);
    return result;
  };

This is correctly working and rendering using stories in setState. But, instead of copying Apollo data, to a new state, I think it's better to directly modify the cache.

But, using cache.modify, it works but, rendering is kind of glitchy. It seems, it first renders the existing list and then, modify cache in the next render. The glitch is around less than a second, but visible to the user.

1 Answers1

0

I fixed it using cache.modify inside, mutation, and using optimistic update.

      moveStoryMutation({
        variables: {
          id: stories[sourceIndex].id,
          sourceIndex,
          destinationIndex,
        },
        optimisticResponse: {
          __typename: "Mutation",
          moveStory: true,
        },
        update: (proxy) => {
          proxy.modify({
            id: proxy.identify(pod),
            fields: {
              stories(existingStoryRefs) {
                return reorder(
                  existingStoryRefs,
                  sourceIndex,
                  destinationIndex
                );
              },
            },
          });