【问题标题】:Apollo Graphql: Avoid loading indicator during refetchApollo Graphql:避免在重新获取期间加载指示器
【发布时间】:2018-03-26 07:17:34
【问题描述】:

我有以下 apollo-graphql 客户端代码,其中我每 30 秒触发一次 graphql 查询并获取数据。

import React, { Component } from 'react';
import { gql, graphql } from 'react-apollo';
import _ from 'underscore';

class Test extends Component {

    render() {
        if (this.props.TestData.loading) {
            return <div>Loading...</div>
        }

        if (this.props.TestData.error && this.props.TestData.error !== null) {
            return <div>Error...</div>
        }

        // Iterate through the this.props.TestData.getTestData and build the Table of data here
        return (
            <table>
                _.map(this.props.TestData.getTestData.testList, (test) => {
                    <tr>
                        <td>{test.testName}</td>
                        <td>{test.status}</td>
                    </tr>
                })
            </table>
        );
    }

}

const TestQuery = gql`
    query TestQuery() {
        getTestData() {
            testList {
                testName
                status
            }
        }
    }
`;

const options = () => ({
    pollInterval: 30000,
});

const withTestData = graphql(TestQuery, { 
    name: 'TestData',
    options, 
});

export default withTestData(Test);

我面临的问题是每 30 秒后我都会看到 Loading...,因为查询被重新触发。我希望 Loading... 仅在页面启动时显示,此后它应该是平滑更新,我不想向用户显示 Loading... 指示器。不知道如何实现。

【问题讨论】:

    标签: graphql apollo react-apollo apollo-client


    【解决方案1】:

    我知道文档建议使用 data.loading,但在大多数情况下,检查查询结果是否为空也同样有效:

    // Should probably check this first. If you error out, usually your data will be
    // undefined, which means putting this later would result in it never getting
    // called. Also checking if it's not-null is a bit redundant :)
    if (this.props.TestData.error) return <div>Error...</div>
    
    // `testList` will only be undefined during the initial fetch
    // or if the query errors out
    if (!this.props.TestData.getTestData) return <div>Loading...</div>
    
    // Render the component as normal
    return <table>...</table>
    

    请记住,GraphQL 可能会返回一些错误,但仍会返回数据。这意味着在生产环境中,您可能需要更强大的错误处理行为,如果出现任何错误,不一定会阻止页面呈现。

    【讨论】:

    • 太棒了,它奏效了。编辑您的代码,因为缺少否定并修改为指向正确的字段。
    猜你喜欢
    • 2019-04-27
    • 2021-08-15
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2017-11-24
    相关资源
    最近更新 更多