UNPKG

@wordpress/data

Version:
8 lines (7 loc) 2.81 kB
{ "version": 3, "sources": ["../../../src/components/use-dispatch/use-dispatch.js"], "sourcesContent": ["/**\n * Internal dependencies\n */\nimport useRegistry from '../registry-provider/use-registry';\n\n/**\n * @typedef {import('../../types').StoreDescriptor<StoreConfig>} StoreDescriptor\n * @template {import('../../types').AnyConfig} StoreConfig\n */\n/**\n * @typedef {import('../../types').UseDispatchReturn<StoreNameOrDescriptor>} UseDispatchReturn\n * @template StoreNameOrDescriptor\n */\n\n/**\n * A custom react hook returning the current registry dispatch actions creators.\n *\n * Note: The component using this hook must be within the context of a\n * RegistryProvider.\n *\n * @template {undefined | string | StoreDescriptor<any>} StoreNameOrDescriptor\n * @param {StoreNameOrDescriptor} [storeNameOrDescriptor] Optionally provide the name of the\n * store or its descriptor from which to\n * retrieve action creators. If not\n * provided, the registry.dispatch\n * function is returned instead.\n *\n * @example\n * This illustrates a pattern where you may need to retrieve dynamic data from\n * the server via the `useSelect` hook to use in combination with the dispatch\n * action.\n *\n * ```jsx\n * import { useCallback } from 'react';\n * import { useDispatch, useSelect } from '@wordpress/data';\n * import { store as myCustomStore } from 'my-custom-store';\n *\n * function Button( { onClick, children } ) {\n * return <button type=\"button\" onClick={ onClick }>{ children }</button>\n * }\n *\n * const SaleButton = ( { children } ) => {\n * const { stockNumber } = useSelect(\n * ( select ) => select( myCustomStore ).getStockNumber(),\n * []\n * );\n * const { startSale } = useDispatch( myCustomStore );\n * const onClick = useCallback( () => {\n * const discountPercent = stockNumber > 50 ? 10: 20;\n * startSale( discountPercent );\n * }, [ stockNumber ] );\n * return <Button onClick={ onClick }>{ children }</Button>\n * }\n *\n * // Rendered somewhere in the application:\n * //\n * // <SaleButton>Start Sale!</SaleButton>\n * ```\n * @return {UseDispatchReturn<StoreNameOrDescriptor>} A custom react hook.\n */\nconst useDispatch = ( storeNameOrDescriptor ) => {\n\tconst { dispatch } = useRegistry();\n\treturn storeNameOrDescriptor === void 0\n\t\t? dispatch\n\t\t: dispatch( storeNameOrDescriptor );\n};\n\nexport default useDispatch;\n"], "mappings": ";AAGA,OAAO,iBAAiB;AAyDxB,IAAM,cAAc,CAAE,0BAA2B;AAChD,QAAM,EAAE,SAAS,IAAI,YAAY;AACjC,SAAO,0BAA0B,SAC9B,WACA,SAAU,qBAAsB;AACpC;AAEA,IAAO,uBAAQ;", "names": [] }