UNPKG

@wordpress/data

Version:
75 lines (72 loc) 2.73 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _useRegistry = _interopRequireDefault(require("../registry-provider/use-registry")); /** * Internal dependencies */ /** * @typedef {import('../../types').StoreDescriptor<StoreConfig>} StoreDescriptor * @template {import('../../types').AnyConfig} StoreConfig */ /** * @typedef {import('../../types').UseDispatchReturn<StoreNameOrDescriptor>} UseDispatchReturn * @template StoreNameOrDescriptor */ /** * A custom react hook returning the current registry dispatch actions creators. * * Note: The component using this hook must be within the context of a * RegistryProvider. * * @template {undefined | string | StoreDescriptor<any>} StoreNameOrDescriptor * @param {StoreNameOrDescriptor} [storeNameOrDescriptor] Optionally provide the name of the * store or its descriptor from which to * retrieve action creators. If not * provided, the registry.dispatch * function is returned instead. * * @example * This illustrates a pattern where you may need to retrieve dynamic data from * the server via the `useSelect` hook to use in combination with the dispatch * action. * * ```jsx * import { useCallback } from 'react'; * import { useDispatch, useSelect } from '@wordpress/data'; * import { store as myCustomStore } from 'my-custom-store'; * * function Button( { onClick, children } ) { * return <button type="button" onClick={ onClick }>{ children }</button> * } * * const SaleButton = ( { children } ) => { * const { stockNumber } = useSelect( * ( select ) => select( myCustomStore ).getStockNumber(), * [] * ); * const { startSale } = useDispatch( myCustomStore ); * const onClick = useCallback( () => { * const discountPercent = stockNumber > 50 ? 10: 20; * startSale( discountPercent ); * }, [ stockNumber ] ); * return <Button onClick={ onClick }>{ children }</Button> * } * * // Rendered somewhere in the application: * // * // <SaleButton>Start Sale!</SaleButton> * ``` * @return {UseDispatchReturn<StoreNameOrDescriptor>} A custom react hook. */ const useDispatch = storeNameOrDescriptor => { const { dispatch } = (0, _useRegistry.default)(); return storeNameOrDescriptor === void 0 ? dispatch : dispatch(storeNameOrDescriptor); }; var _default = exports.default = useDispatch; //# sourceMappingURL=use-dispatch.js.map