JSPM

@wordpress/api-fetch

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

Utility to call WordPress REST APIs

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

@wordpress/api-fetch

Wrapper around window.fetch to call WordPress REST APIs.

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.