Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use apiFetch instead of window.fetch #50043

Merged
merged 3 commits into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions packages/core-data/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -409,15 +409,15 @@ export const getAutosave =
export const __experimentalGetTemplateForLink =
( link ) =>
async ( { dispatch, resolveSelect } ) => {
// Ideally this should be using an apiFetch call
// We could potentially do so by adding a "filter" to the `wp_template` end point.
// Also it seems the returned object is not a regular REST API post type.
let template;
try {
template = await window
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't recall exactly why initially apiFetch didn't work for me 🤔 I wonder what changed.

.fetch( addQueryArgs( link, { '_wp-find-template': true } ) )
.then( ( res ) => res.json() )
.then( ( { data } ) => data );
// This is NOT calling a REST endpoint but rather ends up with a response from
// an Ajax function which has a different shape from a WP_REST_Response.
template = await apiFetch( {
url: addQueryArgs( link, {
'_wp-find-template': true,
} ),
} ).then( ( { data } ) => data );
MaggieCabrera marked this conversation as resolved.
Show resolved Hide resolved
} catch ( e ) {
// For non-FSE themes, it is possible that this request returns an error.
}
Expand Down
20 changes: 6 additions & 14 deletions packages/edit-site/src/store/test/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,21 +168,13 @@ describe( 'actions', () => {
const ID = 'emptytheme//single';
const SLUG = 'single';

window.fetch = async ( path ) => {
if ( path === '/?_wp-find-template=true' ) {
return {
json: async () => ( { data: { id: ID, slug: SLUG } } ),
};
}

throw {
code: 'unknown_path',
message: `Unknown path: ${ path }`,
};
};

apiFetch.setFetchHandler( async ( options ) => {
const { method = 'GET', path } = options;
const { method = 'GET', path, url } = options;

// Called with url arg in `__experimentalGetTemplateForLink`
if ( url ) {
return { data: { id: ID, slug: SLUG } };
}

if ( method === 'GET' ) {
if ( path.startsWith( '/wp/v2/types' ) ) {
Expand Down