Pass obtained field to another query in GraphQL

前端 未结 2 415
野趣味
野趣味 2020-12-03 20:53

Imagine the following query:

query {
  user {
    id
  }
  SomeOtherStuff(id: <--- I want to pass the id obtained from user) {
    id
  }
}
2条回答
  •  孤街浪徒
    2020-12-03 21:33

    In GraphQL, fields at each "level" of the request are executed and resolved in parallel. In your example, user and SomeOtherStuff are both fields of the same type (the root Query type) -- so they will be resolved at the same time. That means each query essentially is not aware of the other or what the other resolved to.

    You would have to handle this kind of scenario client side. In other words, request the user first, parse the response for the id and then make the second request.

    Edit: In Apollo, you would utilize compose for this purpose:

    const userQuery = gql`query User { user { id } }`;
    const stuffQuery = gql`query SomeOtherStuff($id: ID) { someOtherStuff(id: $id){ stuff } }`;
    
    export default compose(
      graphql(userQuery, { name: 'userData' })
      graphql(stuffQuery, { name: 'stuffData', options: ({userData:{id}={}}) => ({variables: {id}}) }),
    )(YourComponent)
    

提交回复
热议问题