【问题标题】:Use result for first query in second query with Apollo Client?在 Apollo Client 的第二个查询中使用第一个查询的结果?
【发布时间】:2018-07-30 12:12:50
【问题描述】:

我正在使用 Apollo、React 和 Graphcool。我有一个查询来获取登录的用户 ID:

const LoginServerQuery = gql`
    query LoginServerQuery {
        loggedInUser {
            id
        }
    }
`;

我需要在另一个从同一个 React 组件调用的查询中使用返回的 ID。这里我硬编码了“xxxxxxxxxxxxxxx”,这是动态用户 ID 需要去的地方:

const LocationQuery = gql`
    query LocationsQuery {
        User(id: "xxxxxxxxxxxxx") {
            location {
                name
            }
        }
    }
`;

【问题讨论】:

    标签: apollo-client


    【解决方案1】:

    如果你像这样导入 compose:

    import { graphql, compose } from 'react-apollo';
    

    然后你可以将 props 传递给第二个查询:

    const LoginServerQuery = gql`
        query LoginServerQuery {
            loggedInUser {
                id
            }
        }
    `;
    
    const LocationsQuery = gql`
        query LocationsQuery($userId: ID) {
            User(id: $userId) {
                name
                location {
                    machineName
                }
            }
        }
    `;
    
    export default compose(
        graphql(LoginServerQuery, { name: 'LoginServerQuery' }),
        graphql(LocationsQuery, {
            name: 'LocationsQuery',
            options: ownProps => ({
                variables: {
                    userId: ownProps.LoginServerQuery.loggedInUser.id,
                },
            }),
        }),
    )(LocationsPage);
    

    更新 - 实际上这不是很好。如果我在不同的页面上,我会刷新,然后导航到这个页面,它会出错。但是,如果我在此页面上刷新它就可以正常工作。

    更新 - 我认为这是一个 Graphcool 问题。我正在刷新的另一个页面也返回了用户。我需要在两个 React 组件中返回 User 的 ID,否则缓存会混淆。添加 ID 字段后,它现在可以工作了。

    https://www.graph.cool/forum/t/the-store-already-contains-an-id-of/218

    【讨论】:

    • 嗨,我是阿波罗的新手。作曲顺序从上到下重要吗?
    • 这是否意味着两个查询都将在单个请求-响应对中执行?
    【解决方案2】:

    这可以像上面那样完成,确保你使用跳过属性,因为你的第一个查询最初是未定义的:

    export default compose(
      graphql(firstQuery, {
        name: 'firstQuery'
      }),
      graphql(secondQuery, { 
        name: 'secondQuery',
        skip: ({ firstQuery }) => !firstQuery.data,
        options: ({firstQuery}) => ({
          variables: {
             var1: firstQuery.data.someQuery.someValue
          }
        })
      })
    )
    

    请看这里:How to chain two GraphQL queries in sequence using Apollo Client

    【讨论】:

      猜你喜欢
      • 2013-11-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 1970-01-01
      • 2018-03-15
      • 2021-01-11
      • 2018-12-18
      相关资源
      最近更新 更多