使用 Apollo Client 在第二个查询中使用第一个查询的结果?

Use result for first query in second query with Apollo Client?

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

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

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

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

如果你像这样导入 compose:

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

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

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 问题。我刷新的另一个页面也是 returning 用户。我需要 return 两个 React 组件中用户的 ID,否则缓存会变得混乱。添加 ID 字段后,它现在可以工作了。

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

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

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

看这里: