DEV Community

Tomasz Kudlinski
Tomasz Kudlinski

Posted on

2 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay