How to correctly replace the item in Apollo cache by the real one?

147 views Asked by At

I'm trying to create a chat app and the messages come as a paginated graphql response from the server that contains a list of the messages. When the user creates a message I create a message in the Apollo cache first to show some optimistic result while the server request is processing.

When the server responds with the create message data as a response in the mutation -> update method I need to replace the existing cache item with the real one. I'm wondering about the best way to do it.

Basically, Apollo cache is normalized, so I can delete the cached item by the ref. But how to know at what index/place in cache this item was to put the real message at that place? There will be a lot of other real messages.

Theoretically, I could brute force and iterate all the existing cached messages to find the relative one by just:

edges.filter((item, index) => {  
  if (item.ref ==== cachedMsgRef) {
   // save the index for the further splice operation and insert the real item
   return true;
  } else {
   return false;
   }
}) 

... splice the real item into the edges list and return in

and in this way, I'll get the appropriate index and will be able to replace the cached item in the edges array with the real one. However, I doubt the performance because this process will be executed for every message, and what if there will be thousands of messages, so the algorithm will need to iterate all of them every time.

Here is the example of the paginated cached messages array with the cached item:

"channelMessages": {
    "edges": [
        {
            "cursor": "NjJlZmFjZDVlZmU4OGIzYmE0ZTEzYzlj",
            "node": {
                // The cached message ID
                "id": "cached-id",
                "text": "some text",
                "__typename": "MessagePayload",
            },
            "__typename": "MessagePayloadEdge"
        },
    ],
    "lastReadAt": 1655989119272,
    "totalCount": 1,
    "newMessagesCount": 1,
    "pageInfo": {
        "hasNextPage": false,
        "startCursor": "NjJlZmFjZDVlZmU4OGIzYmE0ZTEzYzlj",
        "endCursor": "NjJlZmFjZDVlZmU4OGIzYmE0ZTEzYzlj",
        "hasPreviousPage": false,
        "count": 1,
        "__typename": "PageInfo"
    },
    "__typename": "MessageConnectionPayload"
}

Here is the message response that comes from the createMessage mutation:

{
    "__typename": "MessagePayload",
    // the real message ID
    "id": "62efb1deefe88b3ba4e13edc",
    "text": "some text",
}

So I'm wondering what is the best way to do such replacement in the Apollo cache?

I appreciate any info or help!

0

There are 0 answers