Skip to content

Commit

Permalink
Add mutations data and helper functions to __experimentalUseEntityRecord
Browse files Browse the repository at this point in the history
  • Loading branch information
adamziel committed Apr 4, 2022
1 parent 2e4e079 commit 8501dc7
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions packages/core-data/src/hooks/use-entity-record.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* WordPress dependencies
*/
import { useDispatch, useSelect } from '@wordpress/data';
import { useMemo } from '@wordpress/element';

/**
* Internal dependencies
*/
Expand All @@ -9,11 +15,25 @@ interface EntityRecordResolution< RecordType > {
/** The requested entity record */
record: RecordType | null;

/** The edited entity record */
editedRecord: Partial< RecordType >;

/** Apply edits to the edited entity record */
edit: ( diff: Partial< RecordType > ) => void;

/** Persist the edits to the server */
save: () => Promise< void >;

/**
* Is the record still being resolved?
*/
isResolving: boolean;

/**
* Does the record have any edits?
*/
hasEdits: boolean;

/**
* Is the record resolved by now?
*/
Expand Down Expand Up @@ -66,7 +86,28 @@ export default function __experimentalUseEntityRecord< RecordType >(
recordId: string | number,
options: Options = { enabled: true }
): EntityRecordResolution< RecordType > {
const { data: record, ...rest } = useQuerySelect(
const { editEntityRecord, saveEditedEntityRecord } = useDispatch(
coreStore
);

const mutations = useMemo(
() => ( {
edit: ( record ) =>
editEntityRecord( kind, name, recordId, record ),
save: () => saveEditedEntityRecord( kind, name, recordId ),
} ),
[ recordId ]
);

const { editedRecord, hasEdits } = useSelect(
( select ) => ( {
editedRecord: select( coreStore ).getEditedEntityRecord(),
hasEdits: select( coreStore ).hasEditsForEntityRecord(),
} ),
[ kind, name, recordId ]
);

const { data: record, ...querySelectRest } = useQuerySelect(
( query ) => {
if ( ! options.enabled ) {
return null;
Expand All @@ -78,6 +119,9 @@ export default function __experimentalUseEntityRecord< RecordType >(

return {
record,
...rest,
editedRecord,
hasEdits,
...querySelectRest,
...mutations,
};
}

0 comments on commit 8501dc7

Please sign in to comment.