Multiple Network Calls on read, write apollo cache
Tags: nextjs, hooks, apollo, javascript
Published: 2021-05-18 06:11:59

Hi, This is the ecommerce project that i am working on. I am using Nextjs framework with Apollo client 3. While doing add to cart mutation i am using read and write Apollo cache function to update the total items in the cart, but some how it is still hitting database when writing to cache. I can see 2 network calls that is - 

- For AddToCart mutation which is perfectly fine.
- For Cart Query (which is i think wrong), as i could have directly use refetchQuery function to do the same.

```
import { useQuery, useMutation } from "@apollo/client";
import cookie from "react-cookies";

import {
  ALLCATEGORIES,
  SUBCATEGORIES,
  CART_QUERY,
  SESSIONID,
} from "apollo/queries";

import { CART_MUTATION } from "apollo/mutations";

var sessionid = cookie.load("sessionid");
var token = localStorage.getItem('auth');

export const useGetCategories = () => useQuery(ALLCATEGORIES);
export const useGetSessionId = () => useQuery(SESSIONID);
export const useCart = (options) => useQuery(CART_QUERY, options);
export const useProductListing = (options) => useQuery(SUBCATEGORIES, options);

export const useAddToCart = () =>
  useMutation(CART_MUTATION, {
    update(cache, { data: { addToCart } }) {
      try {
        const data = cache.readQuery({
          query: CART_QUERY,
          variables: {
            sessionId: sessionid,
            token: token,
          },
        });
        cache.writeQuery({
          query: CART_QUERY,
          variables: {
            sessionId: sessionid,
            token: token,
          },
          data: {
            cart: [data.cart, addToCart],
          },
        });
      } catch (error) {
        console.log("error", error);
      }
    },
  });

```


```
import styled from "styled-components";
import Rup from "../../icons/rupee.svg";
import ProductImage from "public/product.png";
import { fontWeight, flexbox, fontSize } from "@/styles/global-styles";
import { LazyLoadImage } from "react-lazy-load-image-component";
import { useAddToCart } from "apollo/actions";
import cookie from "react-cookies";
import Loading from "@/components/loader";

const Products = ({ products }) => {
  var sessionid = cookie.load("sessionid");
  const [addToCart, { loading }] = useAddToCart();

  const handleAddToCart = async (uuid) => {
    await addToCart({
      variables: {
        sessionId: sessionid,
        product: uuid,
        quantity: 1,
        monogram: "",
        monogramType: "",
      },
    });
  };

  if (loading) return <Loading />;

  return (
    <>
      <ProductContainer>
        {products.map((product, index) => {
          return (
            <ProductCard key={index}>
              <Badge>Our Bestseller</Badge>
              <ProductThumb>
                <LazyLoadImage src={ProductImage} height={436} effect="blur" />
              </ProductThumb>
              <ProductDetails>
                <ProductName>{product.name}</ProductName>
                <Subtitle>{product.subtitle}</Subtitle>
                <PriceContainer>
                  <Price>
                    <Rup />
                    <span>{product.specialPrice}</span>
                    {product.specialPrice != product.price ? (
                      <CrossPrice>{product.price}</CrossPrice>
                    ) : (
                      <></>
                    )}
                  </Price>
                  <Button onClick={() => handleAddToCart(product.uuid)}>
                    add to cart
                  </Button>
                </PriceContainer>
              </ProductDetails>
            </ProductCard>
          );
        })}
      </ProductContainer>
    </>
  );
};

export default Products;

```

Is there something wrong i am doing ? Need help please