@@ -6,30 +6,51 @@ import $ from 'jquery';
66class ImportStatus extends React . Component {
77 constructor ( props ) {
88 super ( props ) ;
9- this . state = { jobs : props . jobs } ;
10- this . pollingInterval = 5000 ;
9+ this . state = { jobs : props . jobs || [ ] } ;
10+ this . pollingInterval = props . pollingInterval || props . polling_interval || 5000 ;
1111 this . chunkSize = 50 ;
1212 this . links = _ . isEmpty ( props . links ) ? [ `${ props . type } /:id` ] : props . links ;
1313 this . withPdf = props . with_pdf || props . withPdf || false ;
1414 }
1515
1616 componentDidMount ( ) {
17- this . intervalFn = setInterval ( this . poll . bind ( this ) , this . pollingInterval ) ;
17+ this . startPolling ( ) ;
1818 }
1919
2020 componentWillUnmount ( ) {
21- clearInterval ( this . intervalFn ) ;
21+ this . poll ( ) ;
2222 }
2323
24+ hasPendingJobs = ( ) => {
25+ return _ . some ( this . state . jobs , job => job . status !== 'done' ) ;
26+ } ;
27+
2428 poll ( ) {
2529 const pendingJobs = _ . compact ( _ . map ( this . state . jobs , ( job , jid ) => ( job . status !== 'done' ? jid : null ) ) ) ;
2630 if ( pendingJobs . length > 0 ) {
27- _ . each ( _ . chunk ( pendingJobs , this . chunkSize ) , jids => this . updateChunkStatus ( jids ) ) ;
31+ const promises = _ . map ( _ . chunk ( pendingJobs , this . chunkSize ) , jids => this . updateChunkStatus ( jids ) ) ;
32+ Promise . all ( promises ) . then ( ( ) => {
33+ this . timeoutFn = setTimeout ( ( ) => this . poll ( ) , this . pollingInterval ) ; // Schedule the next poll
34+ } ) ;
2835 } else {
29- clearInterval ( this . intervalFn ) ;
36+ this . stopPolling ( ) ;
3037 }
3138 }
3239
40+ startPolling = ( ) => {
41+ this . stopPolling ( ) ; // Clear any existing timeout
42+ if ( this . hasPendingJobs ( ) ) {
43+ this . poll ( ) ;
44+ }
45+ } ;
46+
47+ stopPolling = ( ) => {
48+ if ( this . timeoutFn ) {
49+ clearTimeout ( this . timeoutFn ) ;
50+ this . timeoutFn = null ;
51+ }
52+ } ;
53+
3354 updateChunkStatus ( jids ) {
3455 $ . getJSON ( this . props . pollingPath || this . props . polling_path , {
3556 jids : jids ,
@@ -148,6 +169,8 @@ ImportStatus.propTypes = {
148169 type : PropTypes . string . isRequired ,
149170 polling_path : PropTypes . string . isRequired ,
150171 pollingPath : PropTypes . string . isRequired ,
172+ pollingInterval : PropTypes . number ,
173+ polling_interval : PropTypes . number ,
151174 with_pdf : PropTypes . bool ,
152175 withPdf : PropTypes . bool ,
153176} ;
0 commit comments