useDispatch.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.createDispatchHook = createDispatchHook;
  4. exports.useDispatch = void 0;
  5. var _Context = require("../components/Context");
  6. var _useStore = require("./useStore");
  7. /**
  8. * Hook factory, which creates a `useDispatch` hook bound to a given context.
  9. *
  10. * @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
  11. * @returns {Function} A `useDispatch` hook bound to the specified context.
  12. */
  13. function createDispatchHook(context = _Context.ReactReduxContext) {
  14. const useStore = // @ts-ignore
  15. context === _Context.ReactReduxContext ? _useStore.useStore : (0, _useStore.createStoreHook)(context);
  16. return function useDispatch() {
  17. const store = useStore(); // @ts-ignore
  18. return store.dispatch;
  19. };
  20. }
  21. /**
  22. * A hook to access the redux `dispatch` function.
  23. *
  24. * @returns {any|function} redux store's `dispatch` function
  25. *
  26. * @example
  27. *
  28. * import React, { useCallback } from 'react'
  29. * import { useDispatch } from 'react-redux'
  30. *
  31. * export const CounterComponent = ({ value }) => {
  32. * const dispatch = useDispatch()
  33. * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])
  34. * return (
  35. * <div>
  36. * <span>{value}</span>
  37. * <button onClick={increaseCounter}>Increase counter</button>
  38. * </div>
  39. * )
  40. * }
  41. */
  42. const useDispatch = /*#__PURE__*/createDispatchHook();
  43. exports.useDispatch = useDispatch;