Apollo-client: get all from store just by typename

Created on 18 Apr 2019  ·  11Comments  ·  Source: apollographql/apollo-client

is there any way to get all items from cache data for a specific typename ?
of course by using readFragment I can retrieve an single object by specifying the 'id' property. but I am trying to retrieve an array of all items for a specific typename

⁉️ question 🥦 low-priority 🧞‍♂️ enhancement

Most helpful comment

why is this closed?

All 11 comments

This is not documented, but looking at the source, there is a cache.extract method. You could do this (not tested):

const serializedState = client.cache.extract()

const typeNameItems = Object.values(serializedState)
.filter(item => item.__typename === 'TypeName')
.map(item => client.readFragment({
  fragmentName: 'FragmentName',
  fragment: Fragment,
  id: item.id,
}))

This is not something we currently support, because there's no way of writing a GraphQL query to match all objects of a certain __typename, but as @superandrew213 suggested it is possible to examine the cache data directly, if you're just looking for something that works. Serializing the whole cache just to extract some data may be slow, but maybe that's ok here.

I want re-query my local store, what is the best way to do that ?
Where looping through all store to get items by typename will be slow process and lead for low performance

It would be helpful if we have some wildcard support like get all values which match __typename.

why is this closed?

@benjamn is there any non-slow workaround for this? it seems like being able to have access to all resources of a certain type would be pretty useful.

Please reopen, this would make dealing with cache updates a lot simpler

I'd like to know 1) why people are running into this problem (I am too) and 2) what alternatives or solutions have they found?

I came across this issue by researching for the following use case:

[List- & Detail-Page] After visiting some detail pages the list page should show all visited (cached) items.
I thought it's required to define a type policy that returns all elements of the typename.

Is there some solution for this?

In my case I'm trying to evict a subset of cached objects after a mutation with wider side-effects.
Because there's no straightforward way to determine the affected cached objects ids, I was hoping for a cache.readFragments method that doesn't require an id to be passed. Rather you would read all the fragments , loop through them and determine which should be evicted so the are refetched on the next use.
I didn't find a good solution for this. For now I'm solving my use-case by changing the fetch policy, but that's less than optimal.

An ugly solution would be to have a separate app-level store with the cache ids for the relevant objects, but that would be fragile.

A similar issue has been opened at #6797

Was this page helpful?
0 / 5 - 0 ratings