עמית שוקרון
עמית שוקרון

Reputation: 175

apollo-client refetch queries

I got a cart with items with the option to delete items by your choice, It works nice and you dont need to refresh the page to see results, but if you only add 1 item to the cart and trying to remove that item it won't remove unless you refresh the page.. can't understand why would like to get some hints .

I console logged cart info , if there is more than 1 item it will delete and will console, but if there's only one it won't log and won't delete. ( again, only if I refresh )

Delete product mutation -

const [deleteProduct, { loading: deleteLoading, error: deleteError }] =
    useMutation(DELETE_FROM_CART, {
      variables: { productId, userId: cart?.userId },

      refetchQueries: [
        {
          query: GET_USER_CART,
          variables: { userId: cart?.userId },
          awaitRefetchQueries: true,
        },
      ],
    });

GET_USER_CART:

const GET_USER_CART = gql`
  query ($userId: ID!) {
    getUserCart(userId: $userId) {
      userId
      cartProducts {
        productId
        size
        productPrice
      }
    }
  }
`;


      const { data: cartData, loading: cartLoading } = useQuery(GET_USER_CART, {
    variables: { userId: userInfo?.id },
  });

Also tried to update cache instead refetching query but the same result

  const [deleteProduct, { loading: deleteLoading, error: deleteError }] =
useMutation(DELETE_FROM_CART, {
  variables: { productId, userId: cart?.userId },
  update(cache, { data }) {
    const updatedCart = data?.deleteProductFromCart;
    const existCart = cache.readQuery({
      query: GET_USER_CART,
      variables: { userId: cart?.userId },
    });
    if (existCart && updatedCart) {
      cache.writeQuery({
        query: GET_USER_CART,
        variables: { userId: cart?.userId },
        data: {
          getUserCart: { ...existCart.getUserCart, updatedCart },
        },
      });
    }
  },
});

Upvotes: 5

Views: 11425

Answers (1)

SlothOverlord
SlothOverlord

Reputation: 2037

There are multiple ways to remove the deleted data from cache.

  1. refetchQueries
const [deleteProduct, { loading: deleteLoading, error: deleteError }] =
    useMutation(DELETE_FROM_CART, {
      variables: { productId, userId: cart?.userId },

      refetchQueries: [
        {
          query: GET_USER_CART,
          //Make sure that variables are the same ones as the ones you used to get GET_USER_CART data. If it is different, it wont work. Check if your variables are the same on useQuery you called before and this query
          variables: { userId: cart?.userId },
          awaitRefetchQueries: true,
        },
      ],
    });
  1. refetch. When you use useQuery, you can later use refetch to refetch the data.
const {data, loading, error, refetch} = useQuery(GET_USER_CART, {variables: {}})

const [deleteProduct, { loading: deleteLoading, error: deleteError }] =
    useMutation(DELETE_FROM_CART, {
      variables: { productId, userId: cart?.userId },
onComplete: (data) => {
//call refetch here. 
refetch()
}
    });
  1. update cache
const [deleteProduct, { loading: deleteLoading, error: deleteError }] =
   useMutation(DELETE_FROM_CART, {
     variables: { productId, userId: cart?.userId },
   update(cache, { data }) {
     cache.modify({
       fields: {
         getUserCart(existingCart, { readField }) {
           if (data) {
   //If your existingCart is an object, then use something else instead of filter. I am assuming that your getUserCart returns an array
             return existingCart.filter(
               (taskRef) => data.deleteProductFromCart.id !== readField("id", taskRef)
             );
           }
         },
       },
     });
   },
   });

Upvotes: 9

Related Questions