【问题标题】:Showing loading indicator only on initial load in graphql Query仅在 graphql 查询中的初始加载时显示加载指示器
【发布时间】:2019-08-06 15:46:23
【问题描述】:

我有graphql查询如下:

<Query query={GET_COMPANY_ADDRESSES} variables={{companyId: session.company.id}} notifyOnNetworkStatusChange={true} fetchPolicy={'cache-and-network'}>
    {({loading, error, refetch, data}) => {
        if (loading) return <LoadingIndicator/>;
        if (error) return <ErrorIndicator description={error.message}/>;

        const address = data.companyAddresses[1];

        return (
            <React.Fragment>
                <CollapsiblePanel title="Add slot">
                    <SlotForm address={address} toggleSlotForm={this.toggleSlotForm.bind(this)} refetch={refetch}/>
                </CollapsiblePanel>

            </React.Fragment>

        )
    }}
</Query>

我在初始加载时显示loading indicator。它工作正常。但是我在&lt;SlotForm /&gt; 组件中有表单,我可以在其中向数据库添加记录。表单的提交功能如下:

handleSaveSlot({address}, data) {
        const slot = {
            ...data,
            address: address.id
        };

        return client.mutate({
            variables: {input: slot},
            mutation: ADD_NEW_SLOT,
        })
            .then(result => {
                if (result.data.createSlot.ok) {

                    this.props.refetch();
                    this.setState({hasError: false, errorMessage: "", saved: true, slot: initialSlot()}, () => {
                        setTimeout(() => this.props.toggleSlotForm(false), 3000)
                    });
                }
            })
            .catch(error => {
                let error_msg = error.message.replace("GraphQL error: ", '');
                this.setState({hasError: true, saved: false, errorMessage: error_msg});
                throw(error_msg);
            });
}

.then 回复后,我正在使用this.props.refetch(); 重新获取数据。但是当执行重新获取时,我会在屏幕上更新数据之前再次获得加载指示器。

我想避免这种情况,我不想在每次添加新记录时都显示loading indicator。我只想在初始加载时显示它。

每当我重新获取数据时,我都想“在后台”执行此操作,而不显示加载指示器。

知道怎么做吗?

【问题讨论】:

    标签: reactjs graphql react-apollo


    【解决方案1】:

    像这样改变你的条件应该足够了:

    if (loading && !data.companyAddresses) {
      return <LoadingIndicator/>;
    }
    

    data.companyAddresses 在您的初始查询完成之前将是未定义的,但即使您触发重新获取也应该定义。

    如果可能,您还应该考虑将update 选项与Mutation 组件一起使用,而不是重新获取查询。在突变后手动更新缓存通常比重新获取更好,因为它更快并减少了网络负载。详情请见the docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-21
      • 2012-11-24
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2014-09-02
      相关资源
      最近更新 更多