@wordpress/core-data Edit

Core Data is a data module intended to simplify access to and manipulation of core WordPress entities. It registers its own store and provides a number of selectors which resolve data from the WordPress REST API automatically, along with dispatching action creators to manipulate data. Core data is shipped with TypeScript definitions for WordPress data types.

Used in combination with features of the data module such as subscribe or higher-order components, it enables a developer to easily add data into the logic and display of their plugin.

Installation

Install the module

npm install @wordpress/core-data --save

This package assumes that your code will run in an ES2015+ environment. If you’re using an environment that has limited or no support for such language features and APIs, you should include the polyfill shipped in @wordpress/babel-preset-default in your code.

Top ↑

Example

Below is an example of a component which simply renders a list of authors:

const { useSelect } = wp.data;

function MyAuthorsListBase() {
    const authors = useSelect( ( select ) => {
        return select( 'core' ).getUsers( { who: 'authors' } );
    }, [] );

    if ( ! authors ) {
        return null;
    }

    return (
        <ul>
            { authors.map( ( author ) => (
                <li key={ author.id }>{ author.name }</li>
            ) ) }
        </ul>
    );
}

Top ↑

Actions

The following set of dispatching action creators are available on the object returned by wp.data.dispatch( 'core' ):

Top ↑

addEntities

Returns an action object used in adding new entities.

Parameters

  • entities Array: Entities received.

Returns

  • Object: Action object.

Top ↑

deleteEntityRecord

Action triggered to delete an entity record.

Parameters

  • kind string: Kind of the deleted entity.
  • name string: Name of the deleted entity.
  • recordId string: Record ID of the deleted entity.
  • query ?Object: Special query parameters for the DELETE API call.
  • options [Object]: Delete options.
  • options.__unstableFetch [Function]: Internal use only. Function to call instead of apiFetch(). Must return a promise.
  • options.throwOnError [boolean]: If false, this action suppresses all the exceptions. Defaults to false.

Top ↑

editEntityRecord

Returns an action object that triggers an
edit to an entity record.

Parameters

  • kind string: Kind of the edited entity record.
  • name string: Name of the edited entity record.
  • recordId number: Record ID of the edited entity record.
  • edits Object: The edits.
  • options Object: Options for the edit.
  • options.undoIgnore [boolean]: Whether to ignore the edit in undo history or not.

Returns

  • Object: Action object.

Top ↑

receiveEntityRecords

Returns an action object used in signalling that entity records have been received.

Parameters

  • kind string: Kind of the received entity record.
  • name string: Name of the received entity record.
  • records Array|Object: Records received.
  • query ?Object: Query Object.
  • invalidateCache ?boolean: Should invalidate query caches.
  • edits ?Object: Edits to reset.

Returns

  • Object: Action object.

Top ↑

receiveThemeSupports

Deprecated since WP 5.9, this is not useful anymore, use the selector direclty.

Returns an action object used in signalling that the index has been received.

Returns

  • Object: Action object.

Top ↑

receiveUploadPermissions

Deprecated since WP 5.9, use receiveUserPermission instead.

Returns an action object used in signalling that Upload permissions have been received.

Parameters

  • hasUploadPermissions boolean: Does the user have permission to upload files?

Returns

  • Object: Action object.

Top ↑

redo

Action triggered to redo the last undoed
edit to an entity record, if any.

Top ↑

saveEditedEntityRecord

Action triggered to save an entity record’s edits.

Parameters

  • kind string: Kind of the entity.
  • name string: Name of the entity.
  • recordId Object: ID of the record.
  • options Object: Saving options.

Top ↑

saveEntityRecord

Action triggered to save an entity record.

Parameters

  • kind string: Kind of the received entity.
  • name string: Name of the received entity.
  • record Object: Record to be saved.
  • options Object: Saving options.
  • options.isAutosave [boolean]: Whether this is an autosave.
  • options.__unstableFetch [Function]: Internal use only. Function to call instead of apiFetch(). Must return a promise.
  • options.throwOnError [boolean]: If false, this action suppresses all the exceptions. Defaults to false.

Top ↑

undo

Action triggered to undo the last edit to
an entity record, if any.

Top ↑

Selectors

The following selectors are available on the object returned by wp.data.select( 'core' ):

Top ↑

canUser

Returns whether the current user can perform the given action on the given
REST resource.

Calling this may trigger an OPTIONS request to the REST API via the
canUser() resolver.

https://developer.wordpress.org/rest-api/reference/

Parameters

  • state State: Data state.
  • action string: Action to check. One of: ‘create’, ‘read’, ‘update’, ‘delete’.
  • resource string: REST resource to check, e.g. ‘media’ or ‘posts’.
  • id EntityRecordKey: Optional ID of the rest resource to check.

Returns

  • boolean | undefined: Whether or not the user can perform the action, or undefined if the OPTIONS request is still being made.

Top ↑

canUserEditEntityRecord

Returns whether the current user can edit the given entity.

Calling this may trigger an OPTIONS request to the REST API via the
canUser() resolver.

https://developer.wordpress.org/rest-api/reference/

Parameters

  • state State: Data state.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record’s id.

Returns

  • boolean | undefined: Whether or not the user can edit, or undefined if the OPTIONS request is still being made.

Top ↑

getAuthors

Deprecated since 11.3. Callers should use select( 'core' ).getUsers({ who: 'authors' }) instead.

Returns all available authors.

Parameters

  • state State: Data state.
  • query GetRecordsHttpQuery: Optional object of query parameters to include with request.

Returns

  • ET.User[]: Authors list.

Top ↑

getAutosave

Returns the autosave for the post and author.

Parameters

  • state State: State tree.
  • postType string: The type of the parent post.
  • postId EntityRecordKey: The id of the parent post.
  • authorId EntityRecordKey: The id of the author.

Returns

  • EntityRecord | undefined: The autosave for the post and author.

Top ↑

getAutosaves

Returns the latest autosaves for the post.

May return multiple autosaves since the backend stores one autosave per
author for each post.

Parameters

  • state State: State tree.
  • postType string: The type of the parent post.
  • postId EntityRecordKey: The id of the parent post.

Returns

  • Array< any > | undefined: An array of autosaves for the post, or undefined if there is none.

Top ↑

getBlockPatternCategories

Retrieve the list of registered block pattern categories.

Parameters

  • state State: Data state.

Returns

  • Array< any >: Block pattern category list.

Top ↑

getBlockPatterns

Retrieve the list of registered block patterns.

Parameters

  • state State: Data state.

Returns

  • Array< any >: Block pattern list.

Top ↑

getCurrentTheme

Return the current theme.

Parameters

  • state State: Data state.

Returns

  • any: The current theme.

Top ↑

getCurrentUser

Returns the current user.

Parameters

  • state State: Data state.

Returns

  • undefined< 'edit' >: Current user object.

Top ↑

getEditedEntityRecord

Returns the specified entity record, merged with its edits.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • undefined< EntityRecord > | undefined: The entity record, merged with its edits.

Top ↑

getEmbedPreview

Returns the embed preview for the given URL.

Parameters

  • state State: Data state.
  • url string: Embedded URL.

Returns

  • any: Undefined if the preview has not been fetched, otherwise, the preview fetched from the embed preview API.

Top ↑

getEntitiesByKind

Deprecated since WordPress 6.0. Use getEntitiesConfig instead

Returns the loaded entities for the given kind.

Parameters

  • state State: Data state.
  • kind string: Entity kind.

Returns

  • Array< any >: Array of entities with config matching kind.

Top ↑

getEntitiesConfig

Returns the loaded entities for the given kind.

Parameters

  • state State: Data state.
  • kind string: Entity kind.

Returns

  • Array< any >: Array of entities with config matching kind.

Top ↑

getEntity

Deprecated since WordPress 6.0. Use getEntityConfig instead

Returns the entity config given its kind and name.

Parameters

  • state State: Data state.
  • kind string: Entity kind.
  • name string: Entity name.

Returns

  • any: Entity config

Top ↑

getEntityConfig

Returns the entity config given its kind and name.

Parameters

  • state State: Data state.
  • kind string: Entity kind.
  • name string: Entity name.

Returns

  • any: Entity config

Top ↑

getEntityRecord

Returns the Entity’s record object by key. Returns null if the value is not
yet received, undefined if the value entity is known to not exist, or the
entity object if it exists and is received.

Parameters

  • state State: State tree
  • kind string: Entity kind.
  • name string: Entity name.
  • key EntityRecordKey: Record’s key
  • query GetRecordsHttpQuery: Optional query. If requesting specific fields, fields must always include the ID.

Returns

  • EntityRecord | undefined: Record.

Top ↑

getEntityRecordEdits

Returns the specified entity record’s edits.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • Optional< any >: The entity record’s edits.

Top ↑

getEntityRecordNonTransientEdits

Returns the specified entity record’s non transient edits.

Transient edits don’t create an undo level, and
are not considered for change detection.
They are defined in the entity’s config.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • Optional< any >: The entity record’s non transient edits.

Top ↑

getEntityRecords

Returns the Entity’s records.

Parameters

  • state State: State tree
  • kind string: Entity kind.
  • name string: Entity name.
  • query GetRecordsHttpQuery: Optional terms query. If requesting specific fields, fields must always include the ID.

Returns

  • EntityRecord[] | null: Records.

Top ↑

getLastEntityDeleteError

Returns the specified entity record’s last delete error.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • any: The entity record’s save error.

Top ↑

getLastEntitySaveError

Returns the specified entity record’s last save error.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • any: The entity record’s save error.

Top ↑

getRawEntityRecord

Returns the entity’s record object by key,
with its attributes mapped to their raw values.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • key EntityRecordKey: Record’s key.

Returns

  • EntityRecord | undefined: Object with the entity’s raw attributes.

Top ↑

getRedoEdit

Returns the next edit from the current undo offset
for the entity records edits history, if any.

Parameters

  • state State: State tree.

Returns

  • Optional< any >: The edit.

Top ↑

getReferenceByDistinctEdits

Returns a new reference when edited values have changed. This is useful in
inferring where an edit has been made between states by comparison of the
return values using strict equality.

Usage

const hasEditOccurred = (
   getReferenceByDistinctEdits( beforeState ) !==
   getReferenceByDistinctEdits( afterState )
);

Parameters

  • state State: Editor state.

Returns

  • A value whose reference will change only when an edit occurs.

Top ↑

getThemeSupports

Return theme supports data in the index.

Parameters

  • state State: Data state.

Returns

  • any: Index data.

Top ↑

getUndoEdit

Returns the previous edit from the current undo offset
for the entity records edits history, if any.

Parameters

  • state State: State tree.

Returns

  • Optional< any >: The edit.

Top ↑

getUserQueryResults

Returns all the users returned by a query ID.

Parameters

  • state State: Data state.
  • queryID string: Query ID.

Returns

  • undefined< 'edit' >[]: Users list.

Top ↑

hasEditsForEntityRecord

Returns true if the specified entity record has edits,
and false otherwise.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • boolean: Whether the entity record has edits or not.

Top ↑

hasEntityRecords

Returns true if records have been received for the given set of parameters,
or false otherwise.

Parameters

  • state State: State tree
  • kind string: Entity kind.
  • name string: Entity name.
  • query GetRecordsHttpQuery: Optional terms query.

Returns

  • boolean: Whether entity records have been received.

Top ↑

hasFetchedAutosaves

Returns true if the REST request for autosaves has completed.

Parameters

  • state State: State tree.
  • postType string: The type of the parent post.
  • postId EntityRecordKey: The id of the parent post.

Returns

  • boolean: True if the REST request was completed. False otherwise.

Top ↑

hasRedo

Returns true if there is a next edit from the current undo offset
for the entity records edits history, and false otherwise.

Parameters

  • state State: State tree.

Returns

  • boolean: Whether there is a next edit or not.

Top ↑

hasUndo

Returns true if there is a previous edit from the current undo offset
for the entity records edits history, and false otherwise.

Parameters

  • state State: State tree.

Returns

  • boolean: Whether there is a previous edit or not.

Top ↑

isAutosavingEntityRecord

Returns true if the specified entity record is autosaving, and false otherwise.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • boolean: Whether the entity record is autosaving or not.

Top ↑

isDeletingEntityRecord

Returns true if the specified entity record is deleting, and false otherwise.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • boolean: Whether the entity record is deleting or not.

Top ↑

isPreviewEmbedFallback

Determines if the returned preview is an oEmbed link fallback.

WordPress can be configured to return a simple link to a URL if it is not embeddable.
We need to be able to determine if a URL is embeddable or not, based on what we
get back from the oEmbed preview API.

Parameters

  • state State: Data state.
  • url string: Embedded URL.

Returns

  • boolean: Is the preview for the URL an oEmbed link fallback.

Top ↑

isRequestingEmbedPreview

Returns true if a request is in progress for embed preview data, or false
otherwise.

Parameters

  • state State: Data state.
  • url string: URL the preview would be for.

Returns

  • boolean: Whether a request is in progress for an embed preview.

Top ↑

isSavingEntityRecord

Returns true if the specified entity record is saving, and false otherwise.

Parameters

  • state State: State tree.
  • kind string: Entity kind.
  • name string: Entity name.
  • recordId EntityRecordKey: Record ID.

Returns

  • boolean: Whether the entity record is saving or not.

Top ↑

Hooks

The following set of react hooks available to import from the @wordpress/core-data package:

Top ↑

useEntityRecord

Resolves the specified entity record.

Usage

import { useEntityRecord } from '@wordpress/core-data';

function PageTitleDisplay( { id } ) {
    const { record, isResolving } = useEntityRecord( 'postType', 'page', id );

    if ( isResolving ) {
        return 'Loading...';
    }

    return record.title;
}

// Rendered in the application:
// <PageTitleDisplay id={ 1 } />

In the above example, when PageTitleDisplay is rendered into an
application, the page and the resolution details will be retrieved from
the store state using getEntityRecord(), or resolved if missing.

import { useDispatch } from '@wordpress/data';
import { useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { TextControl } from '@wordpress/components';
import { store as noticeStore } from '@wordpress/notices';
import { useEntityRecord } from '@wordpress/core-data';

function PageRenameForm( { id } ) {
    const page = useEntityRecord( 'postType', 'page', id );
    const { createSuccessNotice, createErrorNotice } =
        useDispatch( noticeStore );

    const setTitle = useCallback(
        ( title ) => {
            page.edit( { title } );
        },
        [ page.edit ]
    );

    if ( page.isResolving ) {
        return 'Loading...';
    }

    async function onRename( event ) {
        event.preventDefault();
        try {
            await page.save();
            createSuccessNotice( __( 'Page renamed.' ), {
                type: 'snackbar',
            } );
        } catch ( error ) {
            createErrorNotice( error.message, { type: 'snackbar' } );
        }
    }

    return (
        <form onSubmit={ onRename }>
            <TextControl
                label={ __( 'Name' ) }
                value={ page.editedRecord.title }
                onChange={ setTitle }
            />
            <button type="submit">{ __( 'Save' ) }</button>
        </form>
    );
}

// Rendered in the application:
// <PageRenameForm id={ 1 } />

In the above example, updating and saving the page title is handled
via the edit() and save() mutation helpers provided by
useEntityRecord();

Parameters

  • kind string: Kind of the entity, e.g. root or a postType. See rootEntitiesConfig in ../entities.ts for a list of available kinds.
  • name string: Name of the entity, e.g. plugin or a post. See rootEntitiesConfig in ../entities.ts for a list of available names.
  • recordId string | number: ID of the requested entity record.
  • options Options: Optional hook options.

Returns

  • EntityRecordResolution< RecordType >: Entity record data.

Changelog

6.1.0 Introduced in WordPress core.

Top ↑

useEntityRecords

Resolves the specified entity records.

Usage

import { useEntityRecord } from '@wordpress/core-data';

function PageTitlesList() {
    const { records, isResolving } = useEntityRecords( 'postType', 'page' );

    if ( isResolving ) {
        return 'Loading...';
    }

    return (
        <ul>
            { records.map( ( page ) => (
                <li>{ page.title }</li>
            ) ) }
        </ul>
    );
}

// Rendered in the application:
// <PageTitlesList />

In the above example, when PageTitlesList is rendered into an
application, the list of records and the resolution details will be retrieved from
the store state using getEntityRecords(), or resolved if missing.

Parameters

  • kind string: Kind of the entity, e.g. root or a postType. See rootEntitiesConfig in ../entities.ts for a list of available kinds.
  • name string: Name of the entity, e.g. plugin or a post. See rootEntitiesConfig in ../entities.ts for a list of available names.
  • queryArgs Record< string, unknown >: Optional HTTP query description for how to fetch the data, passed to the requested API endpoint.
  • options Options: Optional hook options.

Returns

  • EntityRecordsResolution< RecordType >: Entity records data.

Changelog

6.1.0 Introduced in WordPress core.

Top ↑

useResourcePermissions

Resolves resource permissions.

Usage

import { useResourcePermissions } from '@wordpress/core-data';

function PagesList() {
    const { canCreate, isResolving } = useResourcePermissions( 'pages' );

    if ( isResolving ) {
        return 'Loading ...';
    }

    return (
        <div>
            { canCreate ? <button>+ Create a new page</button> : false }
            // ...
        </div>
    );
}

// Rendered in the application:
// <PagesList />
import { useResourcePermissions } from '@wordpress/core-data';

function Page( { pageId } ) {
    const { canCreate, canUpdate, canDelete, isResolving } =
        useResourcePermissions( 'pages', pageId );

    if ( isResolving ) {
        return 'Loading ...';
    }

    return (
        <div>
            { canCreate ? <button>+ Create a new page</button> : false }
            { canUpdate ? <button>Edit page</button> : false }
            { canDelete ? <button>Delete page</button> : false }
            // ...
        </div>
    );
}

// Rendered in the application:
// <Page pageId={ 15 } />

In the above example, when PagesList is rendered into an
application, the appropriate permissions and the resolution details will be retrieved from
the store state using canUser(), or resolved if missing.

Parameters

  • resource string: The resource in question, e.g. media.
  • id IdType: ID of a specific resource entry, if needed, e.g. 10.

Returns

  • ResourcePermissionsResolution< IdType >: Entity records data.

Changelog

6.1.0 Introduced in WordPress core.

Top ↑

Contributing to this package

This is an individual package that’s part of the Gutenberg project. The project is organized as a monorepo. It’s made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.

To find out more about contributing to this package or Gutenberg as a whole, please read the project’s main contributor guide.