Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Im using Apollo, React and Graphcool. I have a query to get the logged in users ID:

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

I need to use the returned ID in another query which is called from the same React component. Here Ive hardcoded "xxxxxxxxxxxxx" which is where the dynamic user ID needs to go:

const LocationQuery = gql`
    query LocationsQuery {
        User(id: "xxxxxxxxxxxxx") {
            location {
                name
            }
        }
    }
`;
like image 540
Evanss Avatar asked Feb 20 '18 07:02

Evanss


People also ask

How do you use Apollo Client to fetch data?

Apollo Client provides a fetchMore helper function to assist with paginated queries. It enables you to execute the same query with different values for variables (such as the current cursor). Now we can connect fetchMore to a button within the Launches component that fetches additional launches when it's clicked.

How do you pass multiple arguments in GraphQL query?

Multiple arguments can be used together in the same query. For example, you can use the where argument to filter the results and then use the order_by argument to sort them.

Can GraphQL schema have multiple queries?

When doing query batching, the GraphQL server executes multiple queries in a single request. But those queries are still independent from each other. They just happen to be executed one after the other, to avoid the latency from multiple requests.


1 Answers

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

like image 62
Evanss Avatar answered Dec 31 '22 18:12

Evanss