Proposal: Better REST API handling in JavaScript

This call for feedback will be open for the next two weeks until July 18th.

I propose extending the useEntityRecord hook to support editing and deleting WordPress data. It should make building features and plugins on top of WordPress REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. easier.

The hook is a part of @wordpress/core-data, a JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. package providing tools for interacting with the WordPress REST API. You may know coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.-data from Redux selectors, actions, and ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. hooksHooks In WordPress theme and development, hooks are functions that can be applied to an action or a Filter in WordPress. Actions are functions performed when a certain event occurs in WordPress. Filters allow you to modify certain functions. Arguments used to hook both filters and actions look the same. like  getEntityRecord, saveEntityRecords, useSelect.

Today, useEntityRecord enables easy access to data

The useEntityRecord hook enables fetching data with just a single line of code:

import { useEntityRecord } from '@wordpress/core-data';
 
// Inside of a React Component:
function PageTitle() {
    const { record, hasResolved } = 
        useEntityRecord( 'postType', 'page', 15);
    return hasResolved ? record.title : 'Loading...';
}

It was introduced to the GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ repository in PR #38782 and will land in WordPress core in 6.1, the next major releasemajor release A release, identified by the first two numbers (3.6), which is the focus of a full release cycle and feature development. WordPress uses decimaling count for major release versions, so 2.8, 2.9, 3.0, and 3.1 are sequential and comparable in scope..

For comparison, achieving the same result without useEntityRecords requires much more knowledge about the Gutenberg internals:

import { useSelect } from '@wordpress/data';
import { store as coreDataStore } from '@wordpress/core-data';

// Inside of a React Component:
function PageTitle() {
	const { page, hasResolved } = useSelect(
		( select ) => {
			const selectorArgs = ['postType', 'page', 15];
			return {
				page: select( coreDataStore )
					.getEntityRecord( ...selectorArgs ),
				hasResolved: select( coreDataStore )
					.hasFinishedResolution(
						'getEntityRecord',
						selectorArgs
					),
			};
		},
		[]
	);
	return hasResolved ? page.title : 'Loading...';
}

Tomorrow, useEntityRecord could ease editing data

In PR #39595, I proposed taking useEntityRecord one step further to make editing WordPress data equally easy:

const { record, edit, editedRecord, hasEdits, save } =
	useEntityRecord( 'postType', 'page', pageId );

// edit({ title: “My new title” });
// save();

// After React re-render:
// console.log( record.title );
// "My new title"

In comparison, this is how it’s done today:

const {
	editEntityRecord,
	saveEditedEntityRecord,
} = useDispatch( coreStore );

const { record, editedRecord, hasEdits, isSaving, saveError } =
	useSelect(
		( select ) => {
			const args = [ kind, type, id ];

			return {
				editedRecord: select( coreStore )
					.getEditedEntityRecord( ...args ),
				hasEdits: select( coreStore )
					.hasEditsForEntityRecord( ...args ),
				isSaving: select( coreStore )
					.isSavingEntityRecord( ...args ),
				saveError: select( coreStore )
					.getLastEntitySaveError( ...args ),
			};
		},
		[ kind, type, id ]
	);

// editEntityRecord(kind, type, id, { title: “My new title” });
// saveEditedEntityRecord(kind, type, id);

// After React re-render:
// console.log( record.title );
// "My new title"

I combed through the WP Directory and found existing plugins that could already benefit from this pattern.

If this resonates with you, speak out before July 18th!

Introducing new APIs means having to maintain them indefinitely. Therefore, I would like to confirm this proposal offers an attractive solution to a real problem. This post attempts to do just that, and I would love to hear from you! All opinions are welcome, especially if:

  • Your JavaScript code interacts with the WordPress REST API
  • You’re maintaining code that leans on wordpress/core-data
  • You’ve struggled to learn how to use it
  • This new APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. would be helpful for you
  • You’re not convinced there’s a need to introduce such an API

I’m also interested in all the code samples related to editing and saving entity records that you are willing to share. It would be a great way to validate and exercise the proposed API.

This call for feedback will be open for the next two weeks until Jul 18, 2022.

Props to Anne McCarthy (@annezazu) and Grzegorz Ziółkowski (@gziolo) for their help in putting this proposal together.

#editor, #gutenberg, #proposal