useSave.js
39 lines
| 1 | import { __ } from "@wordpress/i18n"; |
| 2 | import { select, useDispatch } from "@wordpress/data"; |
| 3 | import { store as coreStore } from "@wordpress/core-data"; |
| 4 | |
| 5 | export default function useSave() { |
| 6 | const { saveEditedEntityRecord } = useDispatch(coreStore); |
| 7 | |
| 8 | /** |
| 9 | * Handle the form submission |
| 10 | */ |
| 11 | const save = async () => { |
| 12 | // build up pending records to save. |
| 13 | const dirtyRecords = select( |
| 14 | coreStore |
| 15 | ).__experimentalGetDirtyEntityRecords(); |
| 16 | const pendingSavedRecords = []; |
| 17 | |
| 18 | dirtyRecords.forEach(({ kind, name, key }) => { |
| 19 | pendingSavedRecords.push( |
| 20 | saveEditedEntityRecord(kind, name, key, { |
| 21 | throwOnError: true, |
| 22 | }) |
| 23 | ); |
| 24 | }); |
| 25 | |
| 26 | // check values. |
| 27 | const values = await Promise.all(pendingSavedRecords); |
| 28 | if (values.some((value) => typeof value === "undefined")) { |
| 29 | throw { message: "Saving failed." }; |
| 30 | } |
| 31 | |
| 32 | return true; |
| 33 | }; |
| 34 | |
| 35 | return { |
| 36 | save, |
| 37 | }; |
| 38 | } |
| 39 |