Skip to content

Commit

Permalink
Debounce the ServerSideRender component's fetch (#11300)
Browse files Browse the repository at this point in the history
  • Loading branch information
notnownikki authored Nov 12, 2018
1 parent c1ae13e commit 3eb44f4
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions packages/components/src/server-side-render/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies.
*/
import { isEqual } from 'lodash';
import { isEqual, debounce } from 'lodash';

/**
* WordPress dependencies.
Expand Down Expand Up @@ -39,6 +39,9 @@ export class ServerSideRender extends Component {
componentDidMount() {
this.isStillMounted = true;
this.fetch( this.props );
// Only debounce once the initial fetch occurs to ensure that the first
// renders show data as soon as possible.
this.fetch = debounce( this.fetch, 500 );
}

componentWillUnmount() {
Expand All @@ -52,27 +55,32 @@ export class ServerSideRender extends Component {
}

fetch( props ) {
if ( ! this.isStillMounted ) {
return;
}
if ( null !== this.state.response ) {
this.setState( { response: null } );
}
const { block, attributes = null, urlQueryArgs = {} } = props;

const path = rendererPath( block, attributes, urlQueryArgs );

return apiFetch( { path } )
// Store the latest fetch request so that when we process it, we can
// check if it is the current request, to avoid race conditions on slow networks.
const fetchRequest = this.currentFetchRequest = apiFetch( { path } )
.then( ( response ) => {
if ( this.isStillMounted && response && response.rendered ) {
if ( this.isStillMounted && fetchRequest === this.currentFetchRequest && response && response.rendered ) {
this.setState( { response: response.rendered } );
}
} )
.catch( ( error ) => {
if ( this.isStillMounted ) {
if ( this.isStillMounted && fetchRequest === this.currentFetchRequest ) {
this.setState( { response: {
error: true,
errorMsg: error.message,
} } );
}
} );
return fetchRequest;
}

render() {
Expand Down

0 comments on commit 3eb44f4

Please sign in to comment.