2017-10-14 118 views
0

我有以下apollo-graphql客戶端代碼,其中我每30秒觸發一次graphql查詢並獲取數據。Apollo 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...指示器。不知道如何實現這一點。

回答

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返回一些錯誤和數據仍然被返回。這意味着在生產環境中,您可能需要更強大的錯誤處理行爲,如果存在任何錯誤,則不一定會阻止頁面呈現。

+0

太棒了,它工作。編輯您的代碼,因爲有一個否定缺失並修改爲指向正確的字段。 –