| 1 | import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';
|
|---|
| 2 | import { useContext, useMemo } from 'react';
|
|---|
| 3 | import { RechartsReduxContext } from './RechartsReduxContext';
|
|---|
| 4 | var noopDispatch = a => a;
|
|---|
| 5 | export var useAppDispatch = () => {
|
|---|
| 6 | var context = useContext(RechartsReduxContext);
|
|---|
| 7 | if (context) {
|
|---|
| 8 | return context.store.dispatch;
|
|---|
| 9 | }
|
|---|
| 10 | return noopDispatch;
|
|---|
| 11 | };
|
|---|
| 12 | var noop = () => {};
|
|---|
| 13 | var addNestedSubNoop = () => noop;
|
|---|
| 14 | var refEquality = (a, b) => a === b;
|
|---|
| 15 |
|
|---|
| 16 | /**
|
|---|
| 17 | * This is a recharts variant of `useSelector` from 'react-redux' package.
|
|---|
| 18 | *
|
|---|
| 19 | * The difference is that react-redux version will throw an Error when used outside of Redux context.
|
|---|
| 20 | *
|
|---|
| 21 | * This, recharts version, will return undefined instead.
|
|---|
| 22 | *
|
|---|
| 23 | * This is because we want to allow using our components outside the Chart wrapper,
|
|---|
| 24 | * and have people provide all props explicitly.
|
|---|
| 25 | *
|
|---|
| 26 | * If however they use the component inside a chart wrapper then those props become optional,
|
|---|
| 27 | * and we read them from Redux state instead.
|
|---|
| 28 | *
|
|---|
| 29 | * @param selector for pulling things out of Redux store; will not be called if the store is not accessible
|
|---|
| 30 | * @return whatever the selector returned; or undefined when outside of Redux store
|
|---|
| 31 | */
|
|---|
| 32 | export function useAppSelector(selector) {
|
|---|
| 33 | var context = useContext(RechartsReduxContext);
|
|---|
| 34 | var outOfContextSelector = useMemo(() => {
|
|---|
| 35 | if (!context) {
|
|---|
| 36 | return noop;
|
|---|
| 37 | }
|
|---|
| 38 | return state => {
|
|---|
| 39 | if (state == null) {
|
|---|
| 40 | return undefined;
|
|---|
| 41 | }
|
|---|
| 42 | return selector(state);
|
|---|
| 43 | };
|
|---|
| 44 | }, [context, selector]);
|
|---|
| 45 | return useSyncExternalStoreWithSelector(context ? context.subscription.addNestedSub : addNestedSubNoop, context ? context.store.getState : noop, context ? context.store.getState : noop, outOfContextSelector, refEquality);
|
|---|
| 46 | } |
|---|