Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 },
        },
      });
    }
  },
});

>Solution :

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)
             );
           }
         },
       },
     });
   },
   });

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading