question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

TypeError: Cannot read property 'id' of undefined at Object.dataIdFromObject

See original GitHub issue

OS: Windows 10 Pro “apollo-client”: “^1.0.2” “react-apollo”: “^1.0.0-rc.3” “graphql-tools”: “^0.10.1”, “immutability-helper”: “^2.1.2”

So, I have a one to many relationship from Posts to Comments:

    type Comments {
      createdAt: DateTime!
      id: ID!
      posts: Posts @relation(name: "PostsOnComments")
      text: String!
      updatedAt: DateTime!
      user: String!
    }

    type Posts {
      caption: String!
      comments: [Comments!]! @relation(name: "PostsOnComments")
      createdAt: DateTime!
      displaysrc: String!
      id: ID!
      likes: Int
      updatedAt: DateTime!
    }

and a Root_Query:

     export const All_Posts_Comments_Query = gql`
      query allPostsCommentsQuery {
        allPostses {
          id
          displaysrc
          caption
          likes
          comments {
            id
            posts {
              id
            }
            text
            user
          }
        }
      }
    `;

Running Add_Comment_Mutation and Remove_Comment_MutationNew:

    export const Add_Comment_Mutation = gql`
      mutation createComment ($id: ID, $textVal: String!, $userVal: String!) {
        createComments (postsId: $id, text: $textVal, user: $userVal){
          id
          text
          user
        }
      }
    `;

    export const Remove_Comment_MutationNew = gql`
      mutation removeComment ($cid: ID!) {
        deleteComments(id: $cid) {
          id
        }
      }
    `;

do not correctly update reactive cache, and thus my UI does not correctly reflect any additions/deletions of comments, which are triggered by onClick events.

My code is as follows:

removeCommentMutation(commentID) {
    const cid = commentID;

    this.props.client.mutate({
      mutation: Remove_Comment_MutationNew,
      variables: {
        cid,
      },
      update: (proxy, mutationResult) => {
        const query = All_Posts_Comments_Query;  // Root Query
        
        const data = proxy.readQuery({
          query,
        });
        
        data.allPostses.push(mutationResult.deleteComments);
        
        proxy.writeQuery({
          query,
          data,
        });
      },
    })
    .catch(this.handleSubmitError);
  },

Intended outcome:

For update to correctly reflect changes to the cache after the comment mutation, by deleting the corresponding comment from the cache.

Actual outcome:

TypeError: Cannot read property 'id' of undefined
    at Object.dataIdFromObject (http://localhost:7770/static/bundle.js:45269:14)
    at http://localhost:7770/static/bundle.js:38959:39
    at Array.map (native)
    at processArrayValue (http://localhost:7770/static/bundle.js:38949:19)
    at writeFieldToStore (http://localhost:7770/static/bundle.js:38897:23)
    at http://localhost:7770/static/bundle.js:38823:18
    at Array.forEach (native)
    at writeSelectionSetToStore (http://localhost:7770/static/bundle.js:38817:30)
    at writeResultToStore (http://localhost:7770/static/bundle.js:38802:13)
    at TransactionDataProxy.applyWrite (http://localhost:7770/static/bundle.js:39421:10)
    at TransactionDataProxy.writeQuery (http://localhost:7770/static/bundle.js:39394:15)
    at update (http://localhost:7770/static/bundle.js:54227:16)
    at http://localhost:7770/static/bundle.js:39572:61
    at tryFunctionOrLogError (http://localhost:7770/static/bundle.js:39457:17)
    at data (http://localhost:7770/static/bundle.js:39572:18)
    at apolloReducer (http://localhost:7770/static/bundle.js:39789:24)
    at combination (http://localhost:7770/static/bundle.js:23011:30)
    at computeNextEntry (<anonymous>:2:27051)
    at recomputeStates (<anonymous>:2:27351)
    at <anonymous>:2:30904
    at Object.dispatch (http://localhost:7770/static/bundle.js:22434:23)
    at dispatch (<anonymous>:2:31397)
    at http://localhost:7770/static/bundle.js:41210:40
    at http://localhost:7770/static/bundle.js:73262:17
    at Object.dispatch (http://localhost:7770/static/bundle.js:23158:19)
    at http://localhost:7770/static/bundle.js:40597:30
tryFunctionOrLogError @ apollo.umd.js:1410
data @ apollo.umd.js:1521
apolloReducer @ apollo.umd.js:1738
combination @ combineReducers.js:132
computeNextEntry @ VM620629:2
recomputeStates @ VM620629:2
(anonymous) @ VM620629:2
dispatch @ createStore.js:179
dispatch @ VM620629:2
(anonymous) @ apollo.umd.js:3159
(anonymous) @ index.js:14
dispatch @ applyMiddleware.js:45
(anonymous) @ apollo.umd.js:2546

My client reads as follows:

const client = new ApolloClient({
  networkInterface: networkInterfaceWithSubscriptions,
  dataIdFromObject: o => o.id
  /*
  dataIdFromObject: o => {
    if (o.__typename != null && o.id != null) {
      return `${o.__typename}-${o.id}`;
    }
  },
  */
})

What is the issue here?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
TheoMercommented, Apr 10, 2017

So, console logging results in client (See image):

const client = new ApolloClient({
  networkInterface: networkInterfaceWithSubscriptions,
  queryTransformer: addTypename,
  // dataIdFromObject: o => o.id
  
  dataIdFromObject: (result) => {
    console.log("result in apolloClient.js = ", result);
    if (result.__typename != null && result.id != null) {
      return `${result.__typename}-${result.id}`;
    }
    return null;
  },
  
})

shows that a number of objects exist, the last of which is defined as undefined. What am I missing here?

error2

1reaction
thebigredgeekcommented, Apr 10, 2017

This is, quite literally, because you are attempting to access undefined as an object. It appears that you are causing undefined to be shoved through dataIdFromObject somehow. This is a problem with your JavaScript 😦.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Graphql is returning "Cannot read property 'id' of undefined ...
I am trying to display one course and to update course topic, using graphql and apollo-server. This is my code: const { ApolloServer,...
Read more >
Cannot read properties of undefined (reading 'id') - TrackJS
TypeError is a subset of JavaScript Error that is thrown when code attempts to do something that does not exist on the target...
Read more >
Configuring the Apollo Client cache - Apollo GraphQL Docs
To learn how to interact with cached data, see Reading and writing data to the cache. ... It does nothing to protect against...
Read more >
Apollo Cache – Angular - GraphQL Code Generator
const cache = new InMemoryCache({ dataIdFromObject: object ... The first argument is the id of the data you want to read from the...
Read more >
Getting error 'TypeError: Cannot read property 'id' of undefined ...
[Solved]-Getting error 'TypeError: Cannot read property 'id' of ... setItem("object", JSON.stringify(this.props.location.data)); } render() { const {data} ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found