javascriptreactjsapollo-clientreact-apollo

Apollo client, merges objects when 'id' propery is empty


I am querying some data from apollo server with the below structure:

   hero {
    image {
      id
      name
      mimeType
      url
    }
    title
    description
  }
  welcome {
    image {
      id
      name
      mimeType
      url
    }
    title
    description
 }

The data that I receive in the 'response' (in browser dev tools) looks like this:

 hero {
    image {
      "id": ''
      "name": ''
      "mimeType": ''
      "url": ''
      "__typename":"Asset"
    }
    title: 'some title'
    description: 'some description'
    "__typename":"Hero"
  }
  welcome {
    image {
      "id": ''
      "name": ''
      "mimeType": ''
      "url": 'intro/welcome.png'
      "__typename":"Asset"
    }
    title: 'another title'
    description: 'another description'
    "__typename":"Welcome"
 }

But when I console.log the returned data, into the code, I get merged 'image' object, like so:

   hero {
    image {
      "id": '',
      "name": '',
      "mimeType": '',
      "url": 'intro/welcome.png',        <-- welcome.image.url merged here as well.
    }
    title: 'some title',
    description: 'some description',
  }
  welcome {
    image {
      "id": '',
      "name": '',
      "mimeType": '',
      "url": 'intro/welcome.png',
    }
    title: 'another title',
    description: 'another description',
 }

Questions:

So, based on the above i want to understand what is the reason behind this happening. Is it a rule that i have to enable/disable ? Is it a principle that states, 'when there is no id value, I merge the objects' ?

I read in the docs that Apollo client makes unique keys based on id + typename, so in this case, is it confused ? (I concluded that the 'id' must have value always.)

And on the other hand, what is gonna happen if the 'ids' have the same value ?

I attach the source that I consulted, for reference: https://www.apollographql.com/docs/react/caching/cache-field-behavior/#the-merge-function

Thanks.


Solution

  • '' is still a string, and as such a valid identifier, such as '5' or 'foo'.

    Apollo Client assumes that if two elements have the same __typename and id, they are the same object and should be merged together.

    "No id" would mean that either you don't request the id field, or it would come back as null - and in those cases, they would not get merged.

    You can override this behaviour by providing your own dataIdFromObject function - but if you have control over your backend, it would probably better to have it return null in these cases.