React Apollo Delay updating Cache After Mutation

Viewed 251

I tried so hard to update Apollo cache after running Mutation, but i couldn't be able to remove 1 second delay after the mutation.

I followed 'ac3-state-management-examples' for solve this problem, but still couldn't find any problem. This is my client-side code.

export const DELETE_ITEM_IN_CART = gql`
  mutation DeleteItemInCart($cartItemId: String!) {
    DeleteItemInCart(cartItemId: $cartItemId)
  }
`;

export function useDeleteItemInCart() {
  console.log(`DELETION START! ${Date()}`);

  const [mutate, { data, error }] = useMutation<
    DeleteItemInCartType.DeleteItemInCart,
    DeleteItemInCartType.DeleteItemInCartVariables
  >(DELETE_ITEM_IN_CART, {
    update(cache, { data }) {
      const deletedCartItemId = data?.DeleteItemInCart;
      const existingCartItems = cache.readQuery<myCart>({
        query: MY_CART,
      });

      if (existingCartItems && deletedCartItem && existingCartItems.myCart) {
        cache.writeQuery({
          query: MY_CART,
          data: {
            myCart: {
              cartItem: existingCartItems.myCart.cartItem.filter(
                t => t.id !== deletedCartItemId,
              ),
            },
          },
        });

        console.log(`DELETION OVER! ${Date()}`);
      }
    },
  });
  return { mutate, data, error };
}

And here's my server-side mutation

export const DeleteItemInCart = mutationField('DeleteItemInCart', {
  args: {cartItemId: nonNull('String')},
  type: nonNull('String'),
  description: 'Delete an item in my cart',
  resolve: (_, {cartItemId}, ctx) => {
    const {prisma} = ctx;

    try {
      prisma.cartItem.delete({
        where: {
          id: cartItemId,
        },
      });
      return cartItemId;
    } catch (error) {
      return cartItemId;
    }
  },
});

This is an example of Apollo-remote-state-mananagement

export const DELETE_TODO = gql`
  mutation DeleteTodo ($id: Int!) {
    deleteTodo (id: $id) {
      success
      todo {
        id
        text 
        completed
      }
      error {
        ... on TodoNotFoundError {
          message
        }
      }
    }
  }
`

export function useDeleteTodo () {
  const [mutate, { data, error }] = useMutation<
    DeleteTodoTypes.DeleteTodo, 
    DeleteTodoTypes.DeleteTodoVariables
  >(
    DELETE_TODO,
    {
      update (cache, { data }) {
        const deletedTodoId = data?.deleteTodo.todo?.id;
        const allTodos = cache.readQuery<GetAllTodos>({
          query: GET_ALL_TODOS
        });

        cache.writeQuery({
          query: GET_ALL_TODOS,
          data: {
            todos: {
              edges: allTodos?.todos.edges.filter((t) => t?.node.id !== deletedTodoId)
            },
          },
        });
      }
    }
  )

  return { mutate, data, error };
}

Any advice? 1 second delay is inevitable using apollo cache?

  • I took a short video of my issue. i dont think it's inevitable... enter image description here
0 Answers
Related