Search code examples
graphqlrelayjs

Why is fragment data fetched but not accessible by Relay mutation


I have mutation (code) in which I want to delete a node. It has a dependency on the post rowId — which is the primary key of the row in the database — and the viewer id. When the pertaining component (code) gets rendered. The following queries are sent

query Queries {
  viewer {
    id,
    ...F1
  }
}
fragment F0 on Viewer {
  id
}
fragment F1 on Viewer {
  id,
  ...F0
}

and

query Queries($id_0:ID!) {
  post(id:$id_0) {
    id,
    ...F2
  }
}
fragment F0 on Post {
  id,
  rowId
}
fragment F1 on Post {
  rowId,
  id
}
fragment F2 on Post {
  headline,
  body,
  id,
  ...F0,
  ...F1
}

The response I get includes the viewer.id and post.rowId. As you can see here,

{
  "data": {
    "post": {
      "id": "cG9zdDo0",
      "headline": "You hit me with a cricket bat.",
      "body": "Hello.",
      "rowId": 4
    }
  }
}

and here,

{
  "data": {
    "viewer": {
      "id": "viewer"
    }
  }
}

However when I want to pass them to the DeletePostMutation like so this.props.post.id they are undefined. When I inspect this.props.post, I get the following

console


Solution

  • The error suggests that the props passed down to DeletePostMutation is not data fetched by Relay, and looking at the code it seems you are constructing a new object for the post and the viewer as opposed to sending the post and viewer fetched by relay.

    I see you are doing this:

      handleDelete(event) {
        this.props.relay.commitUpdate(
          new DeletePostMutation({
            post: { rowId: this.props.post.rowId },
            viewer: { id: this.props.viewer.id },
          })
        )
      }
    

    Try this instead:

      handleDelete(event) {
        this.props.relay.commitUpdate(
          new DeletePostMutation({
            post: this.props.post,
            viewer: this.props.viewer,
          })
        )
      }
    

    Since you are already composing the GraphQL fragments of DeletePostMutation inside the Post Relay Container then inside DeletePostMutation each prop should have the fields defined in the fragments accessible.