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

查看:129
本文介绍了在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问题.我刷新的另一个页面也返回了User.我需要在两个React组件中返回User的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-ready-contains-an-id-of/218

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

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