如何在GraphQL查询中使用变量?

时间:2018-11-07 17:28:00

标签: reactjs react-native graphql

所以我必须做两个查询。首先,它将返回一个包含多个对象的数组,我想获取第一个对象的ID,以便在第二个查询中使用它。

问题是我不能使用b_id: props.getBusiness.business[0]._id

任何想法我该如何处理?

const GET_USER_BUSINESS = gql`
  query getUserBusiness {
    getUserBusiness {
        _id
    }
  }
`;

const GET_BUSINESS_JOBS = gql`
  query getBusinessJobs($b_id: ID!) {
    getBusinessJobs(b_id: $b_id ) {
        _id
        name
    }
  }
`;

export default compose(
    withApollo,
    graphql(GET_USER_BUSINESS,
        {
            name: "business"
        }),
    graphql(GET_BUSINESS_JOBS,
        {
            name: "jobs",
            options: (props) => (
                {
                    variables:
                    {
                        b_id: props.getUserBusiness.business[0].b_id
                    }
                }
            )
        })
)(ProposalContainer);

1 个答案:

答案 0 :(得分:0)

事物的结合。默认情况下,一个graphql HOC将名为data的属性向下传递给包含查询数据的包装组件。但是,因为您在HOC的配置中指定了name,所以无论传递什么名称,该道具实际上都将被称为。换句话说,您可以通过以下方式访问_id

props.business.getUserBusiness[0]._id

...如果getUserBusiness返回一个数组。否则:

props.business.getUserBusiness._id

第二,在查询完成之前,props.business将是未定义的。在拥有GET_BUSINESS_JOBS之前,我们可能不希望发送_id查询。因此,我们想将skip函数传递给HOC的配置:

export default compose(
    withApollo,
    graphql(GET_USER_BUSINESS,
        {
            name: "business"
        }),
    graphql(GET_BUSINESS_JOBS,
        {
            name: "jobs",
            skip: (props) => !props.business || !props.business.getUserBusiness[0]
            options: (props) => (
                {
                    variables:
                    {
                        b_id: props.business.getUserBusiness[0]._id
                    }
                }
            )
        })
)(ProposalContainer)