How to get model from cache by id and __typename
See original GitHub issueI want to get model from the cache and update it having a model id and __typename. So, instead of:
const data = proxy.readQuery({ query: TodoAppQuery });
data.todos.push(createTodo);
proxy.writeQuery({ query: TodoAppQuery, data });
do following:
const model = proxy.readModel(__typename, id);
model.todos.push(createTodo);
proxy.writeModel(model);
This approach is much cleaner and readable, produces less boilerplate code and prevents confusion on what query to use to get and update the model (when I have multiple queries returning same models, for example TodoByIdQuery and TodoListQuery)
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Reading and writing data to the cache - Apollo GraphQL Docs
If a type in your cache uses a custom cache ID (or even if it doesn't), you can use the cache.identify method to...
Read more >Updating the Store – Angular - GraphQL Code Generator
import { InMemoryCache } from 'apollo-cache-inmemory'; // If your database has unique IDs across all types of objects, you can use // a...
Read more >GraphQL/Apollo Client: get data from cache if a query is a ...
const cache = new InMemoryCache({ cacheRedirects: { Query: { post: (_, {id}, {getCacheKey}) => getCacheKey({__typename: "Post", id}), }, }, });.
Read more >Global Object Identification - GraphQL
The id field can be extracted out of the response safely, and can be stored for re-use via caching and refetching. Clients can...
Read more >Tips and Tricks for working with Apollo Cache - Medium
When you make any graphQL query, by default Apollo caches the ... by combining its id or _id properties with the __typename defined...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I was also looking for this. Looks like you can do it using
client.cache.data.get
(at least if you’re using apollo-cache-inmemory)This approach probably has pitfalls that I’m not aware of, so use only if you must
Of if you use a custom
dataIdFromObject
function you can use that to get the cache keys