JSPM

@wordpress/api-fetch

1.0.2
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 83307
  • Score
    100M100P100Q164647F
  • License GPL-2.0-or-later

Utility to make WordPress REST API requests.

Package Exports

  • @wordpress/api-fetch
  • @wordpress/api-fetch/build-module

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@wordpress/api-fetch) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

API Fetch

Utility to make WordPress REST API requests. It's a wrapper around window.fetch.

Installation

Install the module

npm install @wordpress/api-fetch --save

Usage

import apiFetch from '@wordpress/api-fetch';

apiFetch( { path: '/wp/v2/posts' } ).then( posts => {
    console.log( posts );
} );

Middlewares

the api-fetch package supports middlewares. Middlewares are functions you can use to wrap the apiFetch calls to perform any pre/post process to the API requests.

Example

import apiFetch from '@wordpress/api-fetch';

apiFetch.use( ( options, next ) => {
    const start = Date.now();
    const result = next( options );
    result.then( () => {
        console.log( 'The request took ' + Date.now() - start );
    } );
    return result;
} );

Built-in middlewares

The api-fetch package provides built-in middlewares you can use to provide a nonce and a custom rootURL.

Nonce middleware

import apiFetch from '@wordpress/api-fetch';

const nonce = "nonce value";
apiFetch.use( apiFetch.createNonceMiddleware( nonce ) );

Root URL middleware

import apiFetch from '@wordpress/api-fetch';

const rootURL = "http://my-wordpress-site/wp-json/";
apiFetch.use( apiFetch.createRootURLMiddleware( nonce ) );



Code is Poetry.