`updater`没有使用Relay Modern,因为`ConnectionHandler.getConnection()`返回`undefined`

时间:2017-06-24 14:28:38

标签: reactjs graphql relayjs relaymodern

我在我的应用中使用了Relay Modern,并尝试使用updater and optimisticUpdater进行突变后更新缓存,但它并不起作用。

基本上,我的Link类型与votes连接 - 这是我的架构的相关部分:

type Link implements Node {
  createdAt: DateTime!
  description: String!
  id: ID!
  postedBy(filter: UserFilter): User
  url: String!
  votes(filter: VoteFilter, orderBy: VoteOrderBy, skip: Int, after: String, before: String, first: Int, last: Int): VoteConnection
}

type Vote implements Node {
  createdAt: DateTime!
  id: ID!
  link(filter: LinkFilter): Link!
  updatedAt: DateTime!
  user(filter: UserFilter): User!
}

# A connection to a list of items.
type VoteConnection {
  # Information to aid in pagination.
  pageInfo: PageInfo

  # A list of edges.
  edges: [VoteEdge]

  # Count of filtered result set without considering pagination arguments
  count: Int!
}

# An edge in a connection.
type VoteEdge {
  # The item at the end of the edge.
  node: Vote

  # A cursor for use in pagination.
  cursor: String
}

我的Link组件的代码请求片段中的votes

class Link extends Component {

  render() {
    const userId = localStorage.getItem(GC_USER_ID)
    return (
      <div>
        {userId && <div onClick={() => this._voteForLink()}>▲</div>}
        <div>{this.props.link.description} ({this.props.link.url})</div>
        <div>{this.props.link.votes.edges.length} votes | by {this.props.link.postedBy ? this.props.link.postedBy.name : 'Unknown'} {this.props.link.createdAt}</div>
      </div>
    )
  }

  _voteForLink = () => {
    const userId = localStorage.getItem(GC_USER_ID)
    const linkId = this.props.link.id
    CreateVoteMutation(userId, linkId, this.props.viewer.id)
  }

}

export default createFragmentContainer(Link, graphql`
  fragment Link_viewer on Viewer {
    id
  }
  fragment Link_link on Link {
    id
    description
    url
    createdAt
    postedBy {
      id
      name
    }
    votes(last: 1000, orderBy: createdAt_DESC) @connection(key: "Link_votes", filters: []) {
      edges {
        node {
          id
          user {
            id
          }
        }
      }
    }
  }
`)

最后,这是CreateVoteMutationupdater

const mutation = graphql`
  mutation CreateVoteMutation($input: CreateVoteInput!) {
    createVote(input: $input) {
      vote {
        id
        link {
          id
        }
        user {
          id
        }
      }
    }
  }
`

export default (userId, linkId, viewerId) => {
  const variables = {
    input: {
      userId,
      linkId,
      clientMutationId: ""
    },
  }

  commitMutation(
    environment,
    {
      mutation,
      variables,
      updater: (proxyStore) => {
        const createVoteField = proxyStore.getRootField('createVote')
        const newVote = createVoteField.getLinkedRecord('vote')

        const viewerProxy = proxyStore.get(viewerId)
        const connection = ConnectionHandler.getConnection(viewerProxy, 'Link_votes')
        // `connection` is undefined, so the `newVote` doesn't get inserted
        if (connection) {
          ConnectionHandler.insertEdgeAfter(connection, newVote)
        }
      },
      onError: err => console.error(err),
    },
  )
}

ConnectionHandler.getConnection(viewerProxy, 'Link_votes')的调用仅返回undefined,因此newVote实际上并未插入。

有人看到我做错了吗?

1 个答案:

答案 0 :(得分:2)

问题:

当您获得连接时:

const connection = ConnectionHandler.getConnection(viewerProxy, 'Link_votes')

您正试图获得连接&#39; Link_votes&#39;在ViewerProxy上。但是,您要做的是在链接上获取连接。

<强>解决方案:

首先,您需要获取添加投票的链接的ID。

const linkId = newVote.getLinkedRecord('link').getValue('id');

然后你想获得链接代理,以便你可以获得正确的连接。

const linkProxy = proxyStore.get(LinkId)

现在您拥有代表您想要连接的链接的链接代理,您现在可以获得该连接。

const connection = ConnectionHandler.getConnection(linkProxy, 'Link_votes')

很好,所以现在你已经得到了联系。这解决了你遇到的问题。

然而还有另一个问题,你继续添加投票的方式是错误的,首先你需要创建一个Edge,然后添加边缘。

首先我们需要创建一个边

const voteEdge = createEdge(proxyStore, connection, newVote, 'VoteEdge');

现在我们有了voteEdge,我们可以将它附加到连接上。

ConnectionHandler.insertEdgeAfter(connection, voteEdge).

现在它应该全部工作了。但是,您可能不应该使用updater函数进行此类操作。您应该使用RANGE_ADD配置https://facebook.github.io/relay/docs/mutations.html#range-add并更改服务器对该突变的响应方式。