Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to prevent arrays inside cached object being overwritten? #6023

Open
isaacmanu opened this issue Jul 2, 2024 · 1 comment
Open

How to prevent arrays inside cached object being overwritten? #6023

isaacmanu opened this issue Jul 2, 2024 · 1 comment

Comments

@isaacmanu
Copy link

isaacmanu commented Jul 2, 2024

Question

Version 4.0.0-beta.4

Hi,

In our schema we have an object like this:

type SimpleUser implements User {

  id: ID!

  books: [Book]

  name: String!

  someObjects: [SomeObject]
}

And we have a CacheKeyGenerator like so:

class ApolloCacheKeyGenerator : CacheKeyGenerator {
    override fun cacheKeyForObject(obj: Map<String, Any?>, context: CacheKeyGeneratorContext): CacheKey? {
        return when (val typename = obj.getOrDefault("__typename", "")) {
            "SimpleUser" -> CacheKey("$typename:${obj["id"]}")
            else -> null
        }
    }
}

We can receive this SimpleUser object from multiple different queries, and each time we receive it, it can contain a different array of Book and SomeObject, which results in the newest received SimpleUser overwriting the previous one. Is there an easy way for me to merge the new and old arrays every time we receive a SimpleUser regardless of which query it comes from?

Thank you!

@BoD
Copy link
Contributor

BoD commented Jul 2, 2024

Hi!

One way is to use the ApolloStore API to manually store a SimpleUser that is a combination of the one existing in the cache, and the one you just received from the network. You'd have to do that at all the places that execute queries that return SimpleUser.

There are also incubating (experimental) APIs that allow to pass the desired merge algorithm, which will be called whenever an object needs to be merged. These exist to help with pagination scenarios but If you are willing to try experimental APIs I believe they could also be used for your use-case.

Both approaches are described in this document. Hope this helps!

@BoD BoD added 🗄️ Normalized cache ⌛ Waiting for info More information is required labels Jul 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants