/
use-dispatch.js
68 lines (65 loc) · 2.38 KB
/
use-dispatch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Internal dependencies
*/
import useRegistry from '../registry-provider/use-registry';
/**
* @typedef {import('../../types').StoreDescriptor<StoreConfig>} StoreDescriptor
* @template 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=undefined]
* @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 { useDispatch, useSelect } from '@wordpress/data';
* import { useCallback } from '@wordpress/element';
* 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 } = useRegistry();
return storeNameOrDescriptor === void 0
? dispatch
: dispatch( storeNameOrDescriptor );
};
export default useDispatch;