पाठ 17 / 25

Client Caching Libraries

Apollo Client, urql, Relay.

Normalised caches

Libraries such as Apollo Client, urql and Relay add caching, loading and error state, and UI framework bindings. A normalised cache stores each object once, keyed by __typename and id, so data fetched by one query updates every component that shows the same object, and mutations returning the changed object refresh the UI automatically. Fetch policies control whether to read from the cache, the network or both. Relay additionally co-locates fragments with components and enforces conventions such as global IDs and connections.

Querying with Apollo Client in React

A sketch based on Apollo Client's React hooks.

import { gql, useQuery } from "@apollo/client";

const PRODUCT = gql`
  query Product($id: ID!) {
    product(id: $id) { id name price }
  }
`;

export function ProductCard({ id }) {
  const { data, loading, error } = useQuery(PRODUCT, {
    variables: { id },
    fetchPolicy: "cache-first",
  });
  if (loading) return <p>Loading...</p>;
  if (error) return <p role="alert">Could not load product.</p>;
  return <h2>{data.product.name}</h2>;
}

Always select id fields

Without id (and __typename, which most clients add automatically) the cache cannot normalise objects.

त्वरित जाँच: How does a normalised cache identify objects?

  • By the time of the request
  • By query text only
  • By type name and id
  • By the HTTP method
Answer

By type name and id — One copy per object.