Skip to content

Commit d264fef

Browse files
smyrickjerelmiller
andauthored
[docs] Update cache-configuration keyFields docs (apollographql#11778)
Co-authored-by: Jerel Miller <[email protected]>
1 parent ef41a67 commit d264fef

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

docs/source/caching/cache-configuration.mdx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,22 @@ const cache = new InMemoryCache({
180180
// array for their keyFields.
181181
keyFields: [],
182182
},
183+
Store: {
184+
// If you need to disable normalization, set the keyFields to false
185+
// and the object will be embedded in the parent
186+
keyFields: false
187+
},
188+
Location: {
189+
// You can also use a function to determine any of the values above.
190+
// The first argument is the reference to the record to be written, and the second is the runtime context
191+
keyFields: (location, context) => {
192+
if (context.readField("state")) {
193+
return ["city", "state", "country"]
194+
} else {
195+
return ["city", "country"]
196+
}
197+
}
198+
}
183199
},
184200
});
185201
```
@@ -195,6 +211,9 @@ This example shows a variety of `typePolicies` with different `keyFields`:
195211
Book:{"title":"Fahrenheit 451","author":{"name":"Ray Bradbury"}}
196212
```
197213
* The `AllProducts` type illustrates a special strategy for a **singleton** type. If the cache will only ever contain one `AllProducts` object and that object has _no_ identifying fields, you can provide an empty array for its `keyFields`.
214+
* The `Store` type provides an example of how you can [disable normalization](https://www.apollographql.com/docs/react/caching/cache-configuration/#disabling-normalization) by setting the keyFields to `false`
215+
* The `Location` type provides an example of using custom fuction given object and runtime context to calculate what fields should be used for the key field selection.
216+
* Keep in mind that the first argument here is a reference to the record that will be written. As such, it does NOT include subselected fields, only scalar fields, and it contains aliases from the operation. If you need to read the real type you can use `context.storeObject`. To read even more indepth about how this function can work the best source will be our own [test cases for the cache policies](https://github.com/apollographql/apollo-client/blob/8bc7d4d406402962bf5151cdd2c5c75c9398d10c/src/cache/inmemory/__tests__/policies.ts#L5543-L5622)
198217

199218
If an object has multiple `keyFields`, the cache ID always lists those fields in the same order to ensure uniqueness.
200219

0 commit comments

Comments
 (0)