DEV Community

Tomasz Kudlinski
Tomasz Kudlinski

Posted on

Apollo Client 3.0 - Reactive Variables in Local State

I have just wanted to share one cool thing, which was recently announced with the premiere of Apollo Client 3.0 - reactive variables in local state.

I think it will insanely improve developer's experience when implementing local state using Apollo.

Below great example from the docs:

1. Define the query

Create local state variable called cartItems

export const GET_CART_ITEMS = gql`
  query GetCartItems {
    cartItems @client
  }
`;

2. Create reactive variable

export const cartItemsVar = makeVar([]);

3. Define policy for the local state field

Use created reactive variable as the source of cartItems local state field

export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        cartItems: {
          read() {
            return cartItemsVar();
          }
        }
      }
    }
  }
});

4. Create component, which will update reactive variable

import { cartItemsVar } from './cache';
// ... other imports

export function AddToCartButton({ productId }) {
  const cartItems = cartItemsVar();
  return (
    <div class="add-to-cart-button">
      <Button onClick={() => cartItemsVar([...cartItems, productId])}>
        Add to Cart
      </Button>
    </div>
  );
}

5. Create component, which will query for local state field

export const GET_CART_ITEMS = gql`
  query GetCartItems {
    cartItems @client
  }
`;

export function Cart() {
  const { data, loading, error } = useQuery(GET_CART_ITEMS);

  if (loading) return <Loading />;
  if (error) return <p>ERROR: {error.message}</p>;

  return (
    <div class="cart">
      <Header>My Cart</Header>
      {data && data.cartItems.length === 0 ? (
        <p>No items in your cart</p>
      ) : (
        <Fragment>
          {data && data.cartItems.map(productId => (
            <CartItem key={productId} />
          ))}
        </Fragment>
      )}
    </div>
  );
}

Summary

After updating the value of reactive variable all queries, which relies on cartItems local state field will be automatically update. That's awesome!

Link to the docs

Top comments (0)