Search code examples
react-nativecachinggraphqlapollo-clientapollo-cache-inmemory

What is the best way caching apollo client for chat applications?


When i use apollo client cache for chat app i get logical error.

I go first room cache shows 10 message for examle and when i click another room this time i get message with last visited room? my cache

const cache = new InMemoryCache({
typePolicies: {
Query: {
  fields: {
    lastRooms: offsetLimitPagination(),
    lastTopics: offsetLimitPagination(),
    topicDetail: offsetLimitPagination(),
    // chatDetail: offsetLimitPagination(),
    chatDetail: {
      keyArgs:['limit'],
      merge(existing=[], incoming=[], { readField }) {
        try {
          let merged = existing 
          const existingIdSet = new Set(merged.map(message => readField("_id", message)));
          if (incoming) {
            incoming = incoming.filter(message => !existingIdSet.has(readField("_id", message)))
          }
          return [...merged, ...incoming]
        } catch (error) {
          console.log("Apollo Cache chatDetail Query fields Erorr:", error);
        }
      }
    }, 
  }
}
},
});

This is rooms

enter image description here

this is first room, has only 2 message

enter image description here

And this is K3 room, has 16 message

enter image description here


Solution

  • It is about keyArgs field. keyArgs field must be what you want to cache by data, you should set keyArgs field as that

    for example if your query param is (room, user, ...) you shoul use keyArgs:["room"] baceuse of cache should be like that for roomDetail:

    const cache = new InMemoryCache({
    typePolicies: {
    Query: {
    fields: {
    lastRooms: offsetLimitPagination(),
    lastTopics: offsetLimitPagination(),
    topicDetail: offsetLimitPagination(),
    chatDetail: {
      keyArgs:['room'],
      merge(existing=[], incoming=[], { readField }) {
        try {
          let merged = existing 
          const existingIdSet = new Set(merged.map(message => readField("_id", message)));
          if (incoming) {
            incoming = incoming.filter(message => !existingIdSet.has(readField("_id", message)))
          }
          return [...merged, ...incoming]
        } catch (error) {
          console.log("Apollo Cache chatDetail Query fields Erorr:", error);
        }
      }
    }, 
    }
    }
    },
    });