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

耗尽温柔 提交于 2019-12-01 08:27:33

If you import compose like so:

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

Then you can pass the props to the second query with this:

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

UPDATE - Actually this isn't working well. If Im on a different page, I refresh, then navigate to this page it errors. However If I then refresh when on this page it works fine.

UPDATE - I think it was a Graphcool issue. The other page that I was refreshing on was also returning the User. I needed to return the ID for the User in both React components, otherwise the caching got confused. After adding the ID field it now works.

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

This can be done as above, ensure you use skip property as your first query will be undefined initially:

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

See here: How to chain two GraphQL queries in sequence using Apollo Client

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!