Skip to content

Conversation

@renatho
Copy link
Contributor

@renatho renatho commented Mar 2, 2023

What?

It fixes an issue with the apiFetch, which is not parsing the response error when using the fetchAllMiddleware.

Notice that it's not ready to be merged because it could cause backward compatibility problems. I didn't have any good idea so far to keep it working with existing implementations parsing the error manually for this case. Any ideas?

Why?

When using the apiFetch, we need to parse the error JSON manually if we have a per_page=-1 in the path. See the problem with more details by running:

apiFetch( { path: '/wp/v2/anything?per_page=-1' } )
	.then( console.log )
	.catch( ( err ) => {
		console.log(
			'See that the error is not parsed when using per_page=-1',
			err
		);
	} );

apiFetch( { path: '/wp/v2/anything?per_page=-1' } )
	.then( console.log )
	.catch( ( err ) => err.json() )
	.then( ( err ) => {
		console.log(
			'See that the error is parsed when we do it manually',
			err
		);
	} );

apiFetch( { path: '/wp/v2/anything' } )
	.then( console.log )
	.catch( ( err ) => {
		console.log(
			'See that the error is parsed when not using the per_page=-1',
			err
		);
	} );

By default, it shouldn't be needed, because the parse option is true and should parse the JSON for us.

How?

It was skipping the parse in case of error because it's forcing parse: false and parsing it later only in case of success. It fixes it by catching the error and parsing it too through the parseAndThrowError.

Testing Instructions

Use the following snippet, and make sure the error is parsed.

apiFetch( { path: '/wp/v2/anything?per_page=-1' } )
	.then( console.log )
	.catch( console.log );

@renatho renatho requested review from mmtr and nerrad as code owners March 2, 2023 21:27
@renatho renatho force-pushed the fix/api-fetch-catch-using-fetch-all-middleware branch from 5879bc2 to a7052a3 Compare March 2, 2023 22:57
// Ensure headers are returned for page 1.
parse: false,
} );
} ).catch( parseAndThrowError );
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notice that parse option will be always be true here because it skips earlier in the first conditional of the fetchAllMiddleware.

@gziolo gziolo added [Type] Bug An existing feature does not function as intended REST API Interaction Related to REST API [Package] API fetch /packages/api-fetch labels Mar 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Package] API fetch /packages/api-fetch REST API Interaction Related to REST API [Type] Bug An existing feature does not function as intended

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants