@hizzlewp/store
v1.3.9
Published
Store utilities for WordPress plugins. Works with hizzle/store composer package.
Readme
Store
This package contains store utilities for the HizzleWP framework.
Installation
npm install @hizzlewp/store
composer require hizzle/storeUsage
import { useCollectionRecords } from '@hizzlewp/store';
// In your component, use the useRecords hook to get the records.
export ListRecords = ( {per_page} ) => {
const { data, total, summary, isResolving, hasResolutionFailed, getResolutionError } = useCollectionRecords( 'noptin', 'subscribers', { per_page } );
// Check if the records are still loading.
if ( isResolving() ) {
return <div>Loading...</div>;
}
// Check if the records failed to load.
if ( hasResolutionFailed() ) {
return <div>Error: { getResolutionError() }</div>;
}
// Render the records.
return (
<div>
<ul>
{ data.map( ( record ) => <li key={ record.id }>{ record.email }</li> ) }
</ul>
<p>Total: { total }</p>
<p>Summary: { summary }</p>
</div>
);
}API
Collection Provider
The CollectionProvider component is used to provide the collection context to the component tree.
import { CollectionProvider } from '@hizzlewp/store';
<CollectionProvider namespace="noptin" collection="subscribers" recordId={ 123 }>
<SubscriberDetails />
</CollectionProvider>recordId is optional. If provided, the component will be rendered with the record context.
CollectionProvider
Context provider component for providing a collection.
Parameters
- props
Object: The component's props. - props.namespace
string: The collection namespace. - props.collection
string: The collection name. - props.recordId
number: The record ID. - props.children
*: The children to wrap.
Returns
Object: The provided children, wrapped with the collection's context provider.
useProvidedCollection
Hook that returns the current collection.
Returns
NamespaceCollection|undefined: The collection config from context.
useProvidedCollectionConfig
Hook that returns the current collection config.
useProvidedRecordId
Hook that returns the closest current record ID.
Parameters
- namespace
string: The namespace of the collection to use, if not provided, the current namespace will be used. - collection
string: The collection name to use, if not provided, the current collection will be used.
Returns
number|undefined: The current record ID from context.
Actions
The following set of dispatching action creators are available on the object returned by wp.data.dispatch( 'hizzlewp/store' ):
addCollectionConfig
Returns an action object used in adding new collection config.
Parameters
- config
CollectionConfig: Collection config.
Returns
CollectionConfigAction: Action object.
batch
Runs multiple store actions at the same time using one API request.
Example:
const [ savedRecord, updatedRecord, deletedRecord ] =
await dispatch( 'hizzlewp/store' ).batch( [
( { saveCollectionRecord } ) => saveCollectionRecord( 'noptin', 'subscribers', { email: '[email protected]', name: 'John Doe' } ),
( { saveEditedCollectionRecord } ) => saveEditedCollectionRecord( 'noptin', 'subscribers', 123 ),
( { deleteCollectionRecord } ) => deleteCollectionRecord( 'noptin', 'subscribers', 123, null ),
] );Parameters
- requests
Array: Array of functions which are invoked simultaneously. Each function is passed an object containingsaveCollectionRecord,saveEditedCollectionRecord, anddeleteCollectionRecord.
Returns
(thunkArgs: Object) => Promise: A promise that resolves to an array containing the return values of each function given inrequests.
bulkDeleteCollectionRecords
Action triggered to bulk delete collection records.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - query
Record<string, any>: Query object. We'll use the query to determine which records to delete. - options
Object: Saving options. - options.throwOnError
boolean: If false, this action suppresses all the exceptions. Defaults to false. - options.fetchHandler
Function: The fetch handler to use. Defaults to apiFetch.
bulkUpdateCollectionRecords
Action triggered to bulk update collection records.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - query
Record<string, any>: Query object. We'll use the query to determine which records to update. - data
Record<string, any>: Data to update the records with. - options
Object: Saving options. - options.throwOnError
boolean: If false, this action suppresses all the exceptions. Defaults to false. - options.fetchHandler
Function: The fetch handler to use. Defaults to apiFetch.
createUndoLevel
Forces the creation of a new undo level.
Returns
Object: Action object.
deleteCollectionRecord
Action triggered to delete a collection record.
Parameters
- namespace
string: Namespace of the deleted collection. - collection
string: Name of the deleted collection. - recordId
number|string: Record ID of the deleted record. - query
?Object: Special query parameters for the DELETE API call.
doBatchCollectionAction
Trigger a batch action on a collection record.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - action
BatchAction: Action to perform. - options
Object: Options for the action. - options.throwOnError
boolean: If false, this action suppresses all the exceptions. Defaults to false. - options.fetchHandler
Function: The fetch handler to use. Defaults to apiFetch.
doRemoteCollectionRecordAction
Trigger a remote action on a collection record.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - recordId
CollectionRecordKey: Record ID of the record to fire the action on. - action
string: Action to perform. - options
Object: Options for the action. - options.throwOnError
boolean: If false, this action suppresses all the exceptions. Defaults to false. - options.fetchHandler
Function: The fetch handler to use. Defaults to apiFetch.
editCollectionRecord
Returns an action object that triggers an edit to a collection record.
Parameters
- namespace
string: Namespace of the edited collection. - collection
string: Collection of the edited collection. - recordId
number|string: Record ID of the edited collection 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.
receiveCollectionRecords
Returns an action object used in signalling that entity records have been received.
Parameters
- namespace
string: Namespace of the received entity records. - collection
string: Collection of the received entity records. - records
Array: Records received. - query
?Object: Query Object. - invalidateCache
?boolean: Should invalidate query caches. - persistedEdits
?Object: Edits to reset. - meta
?Object: Meta information about pagination.
Returns
Object: Action object.
receiveCollectionRecordTabContent
Returns an action object used in signalling that a record's tab content has been received.
Parameters
- namespace
string: Namespace of the record. - collection
string: Collection of the record. - recordId
number|string: Record id of received tab content. - tabName
tabName: The tab name, e.g, overview. - content
any: The tab content.
Returns
Object: Action object.
redo
Action triggered to redo the last undone edit to a collection record, if any.
removeItems
Returns an action object used in signalling that collection records have been deleted and they need to be removed from collections state.
Parameters
- namespace
string: Namespace of the removed collection. - collection
string: Collection of the removed collection. - records
Array|number|string: Record IDs of the removed entities. - invalidateCache
boolean: Controls whether we want to invalidate the cache.
Returns
Object: Action object.
saveCollectionRecord
Action triggered to save an collection record.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - data
Object: Record to be saved. - options
Object: Options for the action. - options.throwOnError
boolean: If false, this action suppresses all the exceptions. Defaults to false. - options.fetchHandler
Function: The fetch handler to use. Defaults to apiFetch.
saveEditedCollectionRecord
Action triggered to save a collection record's edits.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - recordId
Object: ID of the record. - options
Object=: Saving options.
saveSpecifiedCollectionRecordEdits
Action triggered to save only specified properties for the collection record.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - recordId
number|string: ID of the record. - itemsToSave
Array: List of record properties or property paths to save. - options
Object: Saving options.
setSelectedCollectionRecords
Returns an action object used to toggle a record selection for a given query.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - query
Object: Optional query parameters. - recordId
number|string: Record id of received tab content. - selected
boolean: Whether to select the record. - isShiftKey
boolean: Whether the shift key is pressed.
Returns
Object: Action object.
toggleAllCollectionRecordsSelected
Returns an action object used to toggle all records selection for a given query.
Parameters
- namespace
string: Namespace of the collection. - collection
string: Collection name. - query
Object: Optional query parameters.
Returns
Object: Action object.
undo
Action triggered to undo the last edit to a collection record, if any.
Selectors
The following set of selectors are available on the object returned by wp.data.select( 'hizzlewp/store' ):
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
CollectionResource: Entity resource to check. Accepts entity object{ namespace: 'noptin', collection: 'subscribers', id: 1 }.
Returns
boolean | undefined: Whether or not the user can perform the action, orundefinedif the OPTIONS request is still being made.
getCollectionConfig
Returns the collection config given its namespace and collection name.
Parameters
- state
State: Data state. - namespace
string: The namespace of the collections. - collection
string: The collection name.
Returns
CollectionConfig | undefined: Collection config
getCollectionRecord
Returns the Collection's record object by key. Returns null if the record is not yet received, undefined if the record is known to not exist, or the record object if it exists and is received.
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name. - key
CollectionRecordKey: Record's key / id. - query
Record< string, any >: Optional query. If requesting specific fields, fields must always include the ID.
Returns
CollectionRecord | Partial< CollectionRecord > | null | undefined: Record.
getCollectionRecordEdits
Returns the specified collection record's edits.
Parameters
- state
State: State tree. - namespace
string: Record namespace. - collection
string: Record collection. - recordId
CollectionRecordKey: Record ID.
Returns
- The collection record's edits.
getCollectionRecordNonTransientEdits
Returns the specified collection 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 collection's config.
Parameters
- state
State: State tree. - namespace
string: Record namespace. - collection
string: Record collection. - recordId
CollectionRecordKey: Record ID.
Returns
- The collection record's non transient edits.
getCollectionRecordNoResolver
Returns the Collection's record object by key.
Doesn't trigger a resolver nor requests the collection records from the API if the record isn't available in the local state.
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name. - key
CollectionRecordKey: Record's key / id.
Returns
- Record.
getCollectionRecordPermissions
Returns the collection record permissions for the given collection record id.
Parameters
- state
State: Data state. - namespace
string: Collection namespace. - collection
string: Collection name. - id
string: Collection record id.
Returns
- The collection record permissions.
getCollectionRecords
Returns the Collection's records.
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name. - query
Record< string, any >: Optional records query. If requesting specific fields, fields must always include the ID.
Returns
CollectionRecord[] | null: Records.
getCollectionRecordsPermissions
Returns the collection records permissions for the given collection record ids.
getCollectionRecordsTotalItems
Returns the Collection's total available records for a given query (ignoring pagination).
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name. - query
Record< string, any >: Optional terms query. If requesting specific fields, fields must always include the ID.
Returns
number | null: number | null.
getCollectionRecordsTotalPages
Returns the number of available pages for the given query.
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name. - query
Record< string, any >: Optional terms query. If requesting specific fields, fields must always include the ID.
Returns
number | null: number | null.
getCollectionRecordTabContent
Returns the content for a given record and tab.
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name. - recordId
CollectionRecordKey: The record ID. - tabName
string: The tab name.
Returns
- The tab content.
getEditedCollectionRecord
Returns the specified collection record, merged with its edits.
Parameters
- state
State: State tree. - namespace
string: Record namespace. - collection
string: Record collection. - recordId
CollectionRecordKey: Record ID.
Returns
CollectionRecord | undefined: The collection record, merged with its edits.
getIsAllCollectionRecordsSelected
Returns whether all records are selected for a given query.
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name.
getLastCollectionDeleteError
Returns the specified collection record's last delete error.
Parameters
- state
State: State tree. - namespace
string: Record namespace. - collection
string: Record collection. - recordId
CollectionRecordKey: Record ID.
Returns
- The collection record's save error.
getLastCollectionSaveError
Returns the error that occurred while saving the specified collection record, and undefined otherwise.
Parameters
- state
State: State tree. - namespace
string: Record namespace. - collection
string: Record collection. - recordId
CollectionRecordKey: Record ID.
Returns
Error | undefined: Whether the collection record has a save error or not.
getQueriedItems
Returns items for a given query, or null if the items are not known. Caches result both per state (by reference) and per query (by deep equality). The caching approach is intended to be durable to query objects which are deeply but not referentially equal, since otherwise:
getQueriedItems( state, {} ) !== getQueriedItems( state, {} )
Parameters
- state
Object: State object. - query
?Object: Optional query.
Returns
?Array: Query items.
getRawCollectionRecord
Returns the collection's record object by key, with its attributes mapped to their raw values.
Parameters
- state
State: State tree. - namespace
string: The namespace of the collection. - collection
string: The collection name. - key
CollectionRecordKey: Record's key.
Returns
CollectionRecord | undefined: Object with the collection's raw attributes.
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.
getRemoteActionError
Returns the error for a remote action for a specific record.
Parameters
- state
State: The store state. - namespace
string: The namespace of the collection. - collection
string: The name of the collection. - actionName
string: The name of the remote action. - recordId
CollectionRecordKey: The ID of the record.
Returns
Error|undefined: The error for the remote action, if any.
getSelectedCollectionRecords
Returns the selected records for a given query.
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name. - query
Record< string, any >: Optional records query.
Returns
- The selected records.
getUndoManager
Returns the previous edit from the current undo offset for the entity records edits history, if any.
Parameters
- state
State: State tree.
Returns
- The undo manager.
hasCollectionRecords
Returns true if records have been received for the given set of parameters, or false otherwise.
Parameters
- state
State: State tree - namespace
string: The namespace of the collection. - collection
string: The collection name. - query
Record< string, any >: Optional records query.
Returns
boolean: Whether entity records have been received.
hasEditsForCollectionRecord
Returns true if the specified collection record has edits, and false otherwise.
Parameters
- state
State: State tree. - namespace
string: Record namespace. - collection
string: Record collection. - recordId
CollectionRecordKey: Record ID.
Returns
boolean: Whether the collection record has edits or not.
hasRedo
Returns true if there is a next edit from the current undo offset for the collection records edits history, and false otherwise.
Parameters
- state
State: State tree.
Returns
boolean: Whether there is a next edit or not.
hasUndo
Returns true if there is a previous edit from the current undo offset for the collection records edits history, and false otherwise.
Parameters
- state
State: State tree.
Returns
boolean: Whether there is a previous edit or not.
isDeletingCollectionRecord
Returns true if the specified collection record is deleting, and false otherwise.
Parameters
- state
State: State tree. - namespace
string: Record namespace. - collection
string: Record collection. - recordId
CollectionRecordKey: Record ID.
Returns
boolean: Whether the collection record is deleting or not.
isDoingRemoteCollectionRecordAction
Returns whether a remote action is running for a specific record.
Parameters
- state
State: The store state. - namespace
string: The namespace of the collection. - collection
string: The name of the collection. - actionName
string: The name of the remote action. - recordId
CollectionRecordKey: The ID of the record.
Returns
boolean: Whether the remote action is running.
isSavingCollectionRecord
Returns true if the specified collection record is saving, and false otherwise.
Parameters
- state
State: State tree. - namespace
string: Record namespace. - collection
string: Record collection. - recordId
CollectionRecordKey: Record ID.
Returns
boolean: Whether the collection record is saving or not.
Hooks
The following set of react hooks are available to import from the @hizzlewp/store package:
useCollectionRecord
Resolves the specified collection record.
Usage
import { useCollectionRecord } from '@hizzlewp/store';
function SubscriberDisplay( { id } ) {
const { record, isResolving, error } = useCollectionRecord( 'noptin', 'subscribers', id );
if ( isResolving ) {
return 'Loading...';
}
if ( error ) {
return 'Error: ' + error.message;
}
return record.email;
}
// Rendered in the application:
// <SubscriberDisplay id={ 1 } />In the above example, when SubscriberDisplay is rendered into an
application, the subscriber and the resolution details will be retrieved from
the store state using getCollectionRecord(), or resolved if missing.
import { useCallback } from 'react';
import { useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { TextControl } from '@wordpress/components';
import { store as noticeStore } from '@wordpress/notices';
import { useCollectionRecord } from '@hizzlewp/store';
function SubscriberForm( { id } ) {
const subscriber = useCollectionRecord( 'noptin', 'subscribers', id );
const { createSuccessNotice, createErrorNotice } =
useDispatch( noticeStore );
const setEmail = useCallback( ( email ) => {
subscriber.edit( { email } );
}, [ subscriber.edit ] );
if ( subscriber.isResolving ) {
return 'Loading...';
}
if ( subscriber.error ) {
return 'Error: ' + subscriber.error.message;
}
async function onEdit( event ) {
event.preventDefault();
try {
await subscriber.save();
createSuccessNotice( __( 'Subscriber updated.' ), {
type: 'snackbar',
} );
} catch ( error ) {
createErrorNotice( error.message, { type: 'snackbar' } );
}
}
return (
<form onSubmit={ onEdit }>
<TextControl
__nextHasNoMarginBottom
__next40pxDefaultSize
label={ __( 'Email' ) }
value={ subscriber.editedRecord.email }
onChange={ setEmail }
/>
<button type="submit">{ __( 'Save' ) }</button>
</form>
);
}
// Rendered in the application:
// <SubscriberForm id={ 1 } />In the above example, updating and saving the subscriber email is handled
via the edit() and save() mutation helpers provided by
useRecord();
Parameters
- namespace
string: Namespace e.g, noptin. - collection
string: Collection e.g,subscribers. - recordId
CollectionRecordKey: ID of the requested record. - options
Options: Optional hook options.
Returns
RecordResolution< RecordType >: Entity record data.
useCollectionRecords
Resolves the specified collection records.
Usage
import { useRecords } from '@hizzlewp/store';
function SubscribersList() {
const { records, isResolving, error } = useRecords( 'noptin', 'subscribers' );
if ( isResolving ) {
return 'Loading...';
}
if ( error ) {
return 'Error: ' + error.message;
}
return (
<ul>
{records.map(( subscriber ) => (
<li>{ subscriber.email }</li>
))}
</ul>
);
}
// Rendered in the application:
// <SubscribersList />In the above example, when SubscribersList is rendered into an
application, the list of records and the resolution details will be retrieved from
the store state using getCollectionRecords(), or resolved if missing.
Parameters
- namespace
string: Namespace of the entity, e.g.noptin. - collection
string: Collection of the entity, e.g.subscribers. - 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 >: Collection records data.
Changelog
6.1.0 Introduced in WordPress core.
useCollectionRecordTabContent
Resolves the specified collection record's tab content.
Usage
import { useCollectionRecordTabContent } from '@hizzlewp/store';
function SubscriberDisplay( { id } ) {
const { data: overview, isResolving, error } = useCollectionRecordTabContent( 'noptin', 'subscribers', id, 'overview );
if ( isResolving ) {
return 'Loading...';
}
if ( error ) {
return 'Error: ' + error.message;
}
return <RenderOverview overview={ overview } />
}Parameters
- namespace
string: Namespace e.g, noptin. - collection
string: Collection e.g,subscribers. - recordId
CollectionRecordKey: ID of the requested record. - tabName
string: The tab name, e.g, overview.
Returns
- Entity record overview.
useProvidedCollection
Hook that returns the current collection.
Returns
NamespaceCollection|undefined: The collection config from context.
useProvidedCollectionConfig
Hook that returns the current collection config.
useProvidedRecordId
Hook that returns the closest current record ID.
Parameters
- namespace
string: The namespace of the collection to use, if not provided, the current namespace will be used. - collection
string: The collection name to use, if not provided, the current collection will be used.
Returns
number|undefined: The current record ID from context.
useRecordProp
Hook that returns the value and a setter for the specified property of the nearest provided record of the specified namespace and collection.
Parameters
- namespace
string: The record namespace. - collection
string: The record collection. - prop
string: The property name. - _id
[number|string]: An entity ID to use instead of the context-provided one.
Returns
[*, Function, *]: An array where the first item is the property value, the second is the setter and the third is the full value object from REST API containing more information likeraw,renderedandprotectedprops.
