Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const request = async ( options ) => {
const requestId = ++lastApiRequestId;
try {
const job = await apiFetch( options );
// Drop old responses.
if ( lastApiRequestId > requestId ) {
return;
}
setState( job );
return job;
} catch ( error ) {
setState( { error: error.message } );
}
};
requestWidgetUpdater( instanceChanges, callback ) {
const { identifier, instanceId, instance } = this.props;
if ( ! identifier ) {
return;
}
apiFetch( {
path: `/wp/v2/widgets/${ identifier }/`,
data: {
identifier,
instance,
// use negative ids to make sure the id does not exist on the database.
id_to_use: instanceId * -1,
instance_changes: instanceChanges,
},
method: 'POST',
} ).then(
( response ) => {
if ( this.isStillMounted ) {
this.setState( {
form: response.form,
idBase: response.id_base,
id: response.id,
getReviews( order, page = 1 ) {
const { attributes } = this.props;
const { perPage, productId } = attributes;
const { reviews } = this.state;
const orderby = order || this.state.order || attributes.orderby;
if ( ! productId ) {
// We've removed the selected product, or no product is selected yet.
return;
}
apiFetch( {
path: addQueryArgs( `/wc/blocks/products/reviews`, {
order_by: orderby,
page,
per_page: parseInt( perPage, 10 ) || 1,
product_id: productId,
} ),
parse: false,
} ).then( ( response ) => {
if ( response.json ) {
response.json().then( ( newReviews ) => {
const totalReviews = parseInt( response.headers.get( 'x-wp-total' ), 10 );
if ( page === 1 ) {
this.setState( { reviews: newReviews, totalReviews } );
} else {
this.setState( {
reviews: reviews.filter( ( review ) => Object.keys( review ).length ).concat( newReviews ),
get_subscriber_count() {
apiFetch( { path: '/wpcom/v2/subscribers/count' } ).then( count => {
// Handle error condition
if ( ! count.hasOwnProperty( 'count' ) ) {
this.setState( {
subscriberCountString: __( 'Subscriber count unavailable', 'jetpack' ),
} );
} else {
this.setState( {
subscriberCountString: sprintf(
_n( 'Join %s other subscriber', 'Join %s other subscribers', count.count, 'jetpack' ),
count.count
),
} );
}
} );
}
this.setState({ response: null });
}
const { postID, attributes = null, urlQueryArgs = {} } = props;
if (!attributes['terms']) {
// No need to fetch related posts
this.setState({ response: '' });
return this.currentFetchRequest;
}
const path = rendererPath(postID, attributes, urlQueryArgs);
// 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 && fetchRequest === this.currentFetchRequest && response) {
this.setState({ response: response.rendered });
}
})
.catch((error) => {
if (this.isStillMounted && fetchRequest === this.currentFetchRequest) {
this.setState({
response: {
error: true,
errorMsg: error.message,
}
});
}
});
return fetchRequest;
async function foo() {
apiFetch({ path: '/wp/v2/posts' }).then(posts =>
posts.map(({ date, title }) => `Post "${title.rendered}" at ${date}`)
);
const response = await apiFetch({ parse: false });
if (response.ok) {
console.log(await response.json());
}
}
fetchPostSuggestions( search ) {
const searchablePostTypes = this.props.searchablePostTypes || [ 'post' ];
const suggestionsRequest = this.suggestionsRequest = apiFetch( {
path: addQueryArgs( '/wp/v2/search', {
search,
per_page: 20,
subtype: searchablePostTypes.join( ',' ),
} ),
} ).then(
( suggestions ) => {
if ( this.isStillMounted && this.suggestionsRequest === suggestionsRequest ) {
this.setState( {
suggestions: map( suggestions, ( post ) => ( {
id: post.id,
title: decodeEntities( post.title ) || __( '(no title)', 'amp' ),
postType: post.subtype,
} ) ),
loading: false,
} );
componentDidMount() {
if ( WPCOM_ACCESS_TOKEN ) {
this.setState( { isInFlight: true } );
apiFetch( {
path: `/newspack/v1/wizard/newspack-support-wizard/validate-access-token`,
} )
.then( () => {
this.setState( { isInFlight: false, shouldAuthenticate: false } );
} )
.catch( ( { code, message } ) => {
if ( code !== 'invalid_wpcom_token' ) {
this.setState( { errorMessage: message } );
}
saveReturnPath();
this.setState( { isInFlight: false, shouldAuthenticate: true } );
} );
} else {
saveReturnPath();
this.setState( { shouldAuthenticate: true } );
}
useEffect( () => {
apiFetch( {
path: 'wp-graphql-gutenberg/v1/block-registry',
method: 'POST',
data: {
block_types: getBlockTypes(),
},
} ).catch( () => {
createErrorNotice( __( 'Update of block types registry failed.', 'wp-graphql-gutenberg' ) );
} );
}, [] );
function saveSiteOption( option ) {
setSiteOptions( { ...siteOptions, isSaving: true } );
apiFetch( { path: '/wp/v2/settings', method: 'POST', data: { [ siteOption ]: option } } )
.then( () => updatePreviousOption( option ) )
.catch( () => {
createErrorNotice( sprintf( __( 'Unable to save site %s' ), siteOption ) );
revertOption();
} );
}