How to use the @wordpress/api-fetch function in @wordpress/api-fetch

To help you get started, we’ve selected a few @wordpress/api-fetch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Automattic / sensei / assets / data-port / export / export-job-state.js View on Github external
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 } );
		}
	};
github WordPress / gutenberg / packages / block-library / src / legacy-widget / edit / handler.js View on Github external
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,
github woocommerce / woocommerce-gutenberg-products-block / assets / js / blocks / reviews-by-product / block.js View on Github external
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 ),
github Automattic / jetpack / extensions / blocks / subscriptions / edit.js View on Github external
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
					),
				} );
			}
		} );
	}
github keesiemeijer / related-posts-by-taxonomy / editor-block / src / components / RestRequest.js View on Github external
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;
github DefinitelyTyped / DefinitelyTyped / types / wordpress__api-fetch / wordpress__api-fetch-tests.ts View on Github external
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());
    }
}
github ampproject / amp-wp / assets / src / stories-editor / components / post-selector / index.js View on Github external
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,
					} );
github Automattic / newspack-plugin / assets / wizards / support / components / withWPCOMAuth.js View on Github external
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 } );
			}
github pristas-peter / wp-graphql-gutenberg / src / Blocks / registry.js View on Github external
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' ) );
		} );
	}, [] );
github Automattic / wp-calypso / apps / full-site-editing / full-site-editing-plugin / full-site-editing / lib / site-options / use-site-options.js View on Github external
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();
			} );
	}