Search code examples
apolloreact-apolloapollo-client

dataIdFromObject overwriting cache from other queries incorrectly


So using dataIdFromObject as the following:

cache: new InMemoryCache({
      dataIdFromObject: object => {
        switch (object.__typename) {
          case 'AppKey':
            return object.appKeyId
          case 'App':
            return object.appId
          default:
            return defaultDataIdFromObject(object)
        }
      },
    })

is some how rewriting the first object.name in appKey from app, or sometimes vice versa. For example

data.getAppKeys = [{ appKeyId: 1, name: 'My App' }, ...correctObjects] when the backend has the key as {appKeyId: 1, name: 'myAppKey'}. This doesn't occur when commenting out either of the cases from dataIdFromObject.

How can I get the cache to rewrite the correct queries?


Solution

  • You need to have a unique identifier that goes beyond a number, because the numbers will match and the cache will overwrite incorrectly, the solution was is add the __typename into the data identifier like so:

    dataIdFromObject: object => {
            const getID = (typename, id) => `${typename}_${id}`
    
            switch (object.__typename) {
              case 'AppKey':
                return getID(object.__typename, object.appKeyId)
              case 'App':
                return getID(object.__typename, object.appId)
              default:
                return getId(object.__typename, defaultDataIdFromObject(object))
            }
          },
        })