Apollo GraphQL:用apolloClient.query调用两次查询?

时间:2016-11-01 01:45:19

标签: graphql apollo apollo-server

我有以下查询:

const GET_MY_USERINFOFORIMS_QUERY = gql`
query($userID: String!){
  myUserDataForIMs(userID:userID){
    name_first
    name_last
    picture_medium
  }
} `;

const withUserInfoForIMs = graphql(GET_MY_USERINFOFORIMS_QUERY, {
    options({ userID }) {
        return {
            variables: { userID: `${userID}`}
        };
    }
    ,
    props({ data: { loading, myUserDataForIMs } }) {
        return { loading, myUserDataForIMs };
    },
    name: 'GET_MY_USERINFOFORIMS_QUERY',
});

Apollo docs开始,看起来我可以使用apolloClient.query从组件内部调用此查询两次,执行以下操作:

client.query({ query: query1 })
client.query({ query: query2 })

有没有办法调用查询两次,每次传递不同的用户ID?

2 个答案:

答案 0 :(得分:1)

找到它。 :)

        const localThis = this;
        this.props.ApolloClientWithSubscribeEnabled.query({
            query: GET_MY_USERINFOFORIMS_QUERY,
            variables: {userID: fromID},
        }).then((result) => {
            localThis.setState({ fromAvatar: result.data.myUserDataForIMs[0].picture_thumbnail });
        });

        this.props.ApolloClientWithSubscribeEnabled.query({
            query: GET_MY_USERINFOFORIMS_QUERY,
            variables: {userID: toID},
        }).then((result) => {
             localThis.setState({ toAvatar: result.data.myUserDataForIMs[0].picture_thumbnail });
        });

如果有更好/更有效的方式,请发布。

答案 1 :(得分:0)

你可以通过将Apollo的refetch()方法传递到组件的道具和数据旁边来实现这一点:

const withUserInfoForIMs = graphql(GET_MY_USERINFOFORIMS_QUERY, {
    options({ userID }) {
        return {
            variables: { userID: `${userID}`}
        };
    },
    props({ data: { refetch, loading, myUserDataForIMs } }) {
        return { refetch, loading, myUserDataForIMs };
    },
    name: 'GET_MY_USERINFOFORIMS_QUERY',
});

...然后在组件的某个地方,您可以“手动”重新获取数据:

theUserWasChangedSomehow(userID) {
  this.props.refetch({ userID });
}