【问题标题】:Apollo GraphQL: Calling a Query Twice with apolloClient.query?Apollo GraphQL:使用 apolloClient.query 调用两次查询?
【发布时间】:2017-03-14 04:15:42
【问题描述】:

我有以下疑问:

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?

【问题讨论】:

    标签: graphql apollo apollo-server


    【解决方案1】:

    您可以通过将 Apollo 的 refetch() 方法与数据一起传递到组件的 props 中来做到这一点:

    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 });
    }
    

    【讨论】:

      【解决方案2】:

      找到了。 :)

              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 });
              });
      

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

      【讨论】:

        猜你喜欢
        • 2018-02-10
        • 2021-07-04
        • 2018-10-19
        • 2018-10-07
        • 2020-08-01
        • 2017-08-25
        • 1970-01-01
        • 2019-01-07
        • 2021-04-19
        相关资源
        最近更新 更多