Skip to content

Commit

Permalink
Components: Ensure isLoading set to false after request error
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed Jan 16, 2018
1 parent 3e08d83 commit 950e982
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
22 changes: 15 additions & 7 deletions components/higher-order/with-api-data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,16 +139,24 @@ export default ( mapPropsToData ) => ( WrappedComponent ) => {
[ this.getPendingKey( method ) ]: true,
} );

request( { path, method } ).then( ( response ) => {
this.setIntoDataProp( propName, {
[ this.getPendingKey( method ) ]: false,
request( { path, method } )
// [Success] Set the data prop:
.then( ( response ) => ( {
[ this.getResponseDataKey( method ) ]: response.body,
} );
} ).catch( ( error ) => {
this.setIntoDataProp( propName, {
} ) )

// [Failure] Set the error prop:
.catch( ( error ) => ( {
[ this.getErrorResponseKey( method ) ]: error,
} ) )

// Always reset loading prop:
.then( ( nextDataProp ) => {
this.setIntoDataProp( propName, {
[ this.getPendingKey( method ) ]: false,
...nextDataProp,
} );
} );
} );
}

applyMapping( props ) {
Expand Down
30 changes: 27 additions & 3 deletions components/higher-order/with-api-data/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@ import { identity, fromPairs } from 'lodash';
import withAPIData from '../';

jest.mock( '../request', () => {
const request = jest.fn( () => Promise.resolve( {
body: {},
} ) );
const request = jest.fn( ( { path } ) => {
if ( /\/users$/.test( path ) ) {
return Promise.reject( {
code: 'rest_forbidden_context',
message: 'Sorry, you are not allowed to list users.',
data: { status: 403 },
} );
}

return Promise.resolve( { body: {} } );
} );

request.getCachedResponse = ( { method, path } ) => {
return method === 'GET' && '/wp/v2/pages/10' === path ?
Expand All @@ -29,6 +37,9 @@ describe( 'withAPIData()', () => {
'/wp/v2/pages/(?P<parent>[\\d]+)/revisions': {
methods: [ 'GET' ],
},
'/wp/v2/users': {
methods: [ 'GET' ],
},
'/wp/v2/pages/(?P<id>[\\d]+)': {
methods: [
'GET',
Expand Down Expand Up @@ -80,6 +91,19 @@ describe( 'withAPIData()', () => {
} );
} );

it( 'should handle error response', ( done ) => {
const wrapper = getWrapper( () => ( {
users: '/wp/v2/users',
} ) );

process.nextTick( () => {
expect( wrapper.state( 'dataProps' ).users.isLoading ).toBe( false );
expect( wrapper.state( 'dataProps' ).users ).not.toHaveProperty( 'data' );

done();
} );
} );

it( 'should preassign cached data', ( done ) => {
const wrapper = getWrapper( () => ( {
page: '/wp/v2/pages/10',
Expand Down

0 comments on commit 950e982

Please sign in to comment.