From 002e1995609a1281be330224f29ba329d890951d Mon Sep 17 00:00:00 2001 From: Ben Newman Date: Thu, 20 Aug 2020 16:18:43 -0400 Subject: [PATCH] Docs for useReactiveVar. --- .../managing-state-with-field-policies.mdx | 34 +++++++++++++++---- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/docs/source/local-state/managing-state-with-field-policies.mdx b/docs/source/local-state/managing-state-with-field-policies.mdx index a8d0448eeb4..e25ed7b8cec 100644 --- a/docs/source/local-state/managing-state-with-field-policies.mdx +++ b/docs/source/local-state/managing-state-with-field-policies.mdx @@ -147,15 +147,14 @@ This `read` function returns the value of our reactive variable whenever `cartIt Now, let's create a button component that enables the user to add a product to their cart: -```jsx{8}:title=AddToCartButton.js +```jsx{7}:title=AddToCartButton.js import { cartItemsVar } from './cache'; // ... other imports export function AddToCartButton({ productId }) { - const cartItems = cartItemsVar(); return (
-
@@ -167,8 +166,6 @@ On click, this button updates the value of `cartItemsVar` to append the button's Here's a `Cart` component that uses the `GET_CART_ITEMS` query and therefore refreshes automatically whenever the value of `cartItemsVar` changes: - - ```jsx:title=Cart.js export const GET_CART_ITEMS = gql` query GetCartItems { @@ -199,7 +196,32 @@ export function Cart() { } ``` - +Alternatively, you can read directly from a reactive variable using the `useReactiveVar` hook introduced in Apollo Client 3.2.0: + +```jsx:title=Cart.js +import { useReactiveVar } from '@apollo/client'; + +export function Cart() { + const cartItems = useReactiveVar(cartItemsVar); + + return ( +
+
My Cart
+ {cartItems.length === 0 ? ( +

No items in your cart

+ ) : ( + + {cartItems.map(productId => ( + + ))} + + )} +
+ ); +} +``` + +As in the earlier `useQuery` example, whenever the `cartItemsVar` variable is updated, any currently-mounted `Cart` components will rerender. Calling `cartItemsVar()` without `useReactiveVar` will not capture this dependency, so future variable updates will not rerender the component. Both of these approaches are useful in different situations. ### Storing local state in the cache