Apollo GraphQL部分缓存值复用:单条查询能否读取列表缓存字段?
Absolutely! This is one of the core features of Apollo Client's InMemoryCache—it uses normalized caching to automatically reuse existing data from the cache and only fetch missing fields over the network. Here's how it works in your scenario:
1. How the Cache Stores Your Data
First, when you fetch the comments list with comments { id text }, Apollo normalizes each Comment object and stores it in the cache using its id as the unique key. So for comment id:1, the cache will have an entry like:
Comment:1: { id: 1, text: "Your comment text" }
2. Fetching the Single Comment with Missing Fields
When you later run the query for the single comment with author fields, Apollo does two things:
- It checks the cache for
Comment:1and finds the existingidandtextfields. - If you configure your
useQuerycall correctly, it will immediately return this partial data to your component, then send a network request only for the missingauthorfield.
3. Configuring useQuery for Partial Results
To get the immediate partial data while fetching the missing fields, you need to add two key options to your useQuery call:
returnPartialData: true: Tells Apollo to return whatever data is available in the cache right away, even if it's not complete.fetchPolicy: "cache-and-network"(optional but recommended here): Ensures Apollo checks the cache first, then sends a network request to fetch any missing fields.
Here's how your component code would look:
const { data, loading, error } = useQuery(COMMENT_QUERY, { variables: { id: 1 }, returnPartialData: true, fetchPolicy: "cache-and-network" });
4. Handling the Partial Data in Your Component
Your component will receive updates in two stages:
- First render:
datawill contain the cachedidandtextfields, butauthorwill beundefined.loadingwill betruewhile the network request is in flight. - After network response: Once the
authordata comes back, Apollo updates the cache and your component re-renders with the fulldataobject (includingauthor), andloadingbecomesfalse.
Key Notes
- Normalization Requirement: This works because Apollo uses the
idfield as the unique identifier for yourCommenttype (this is the default behavior—if your type used a different unique field, you'd configurekeyFieldsin your cache setup). - No Custom Cache Reading Needed: You don't have to manually read from the cache; Apollo handles this automatically when you use the correct query options.
内容的提问来源于stack exchange,提问作者CaptainStiggz

