在 Apollo Client 的第二个查询中使用第一个查询的结果? [英] Use result for first query in second query with Apollo Client?

查看:42
本文介绍了在 Apollo Client 的第二个查询中使用第一个查询的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我需要在从同一个 React 组件调用的另一个查询中使用返回的 ID.这里我硬编码了xxxxxxxxxxxxx",这是动态用户 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
            }
        }
    }
`;

推荐答案

如果你像这样导入 compose:

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.

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

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

这篇关于在 Apollo Client 的第二个查询中使用第一个查询的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆