You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apollo GraphQL部分缓存值复用:单条查询能否读取列表缓存字段?

Yes, Apollo Client Does This Natively (No Custom Code Needed)

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:1 and finds the existing id and text fields.
  • If you configure your useQuery call correctly, it will immediately return this partial data to your component, then send a network request only for the missing author field.

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:

  1. First render: data will contain the cached id and text fields, but author will be undefined. loading will be true while the network request is in flight.
  2. After network response: Once the author data comes back, Apollo updates the cache and your component re-renders with the full data object (including author), and loading becomes false.

Key Notes

  • Normalization Requirement: This works because Apollo uses the id field as the unique identifier for your Comment type (this is the default behavior—if your type used a different unique field, you'd configure keyFields in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:27:56