From e13e630cd6e4fc0b1ff92098a28a770794c7bb9a Mon Sep 17 00:00:00 2001 From: gabrhr <73925454+gabrhr@users.noreply.github.com> Date: Wed, 20 Apr 2022 10:19:29 -0500 Subject: =?UTF-8?q?A=C3=B1adir=20plantilla?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Base para front --- front/odiparpack/app/utils/injectSaga.js | 59 ++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 front/odiparpack/app/utils/injectSaga.js (limited to 'front/odiparpack/app/utils/injectSaga.js') diff --git a/front/odiparpack/app/utils/injectSaga.js b/front/odiparpack/app/utils/injectSaga.js new file mode 100644 index 0000000..3f8752b --- /dev/null +++ b/front/odiparpack/app/utils/injectSaga.js @@ -0,0 +1,59 @@ +import React from 'react'; +import hoistNonReactStatics from 'hoist-non-react-statics'; +import { ReactReduxContext } from 'react-redux'; + +import getInjectors from './sagaInjectors'; + +/** + * Dynamically injects a saga, passes component's props as saga arguments + * + * @param {string} key A key of the saga + * @param {function} saga A root saga that will be injected + * @param {string} [mode] By default (constants.DAEMON) the saga will be started + * on component mount and never canceled or started again. Another two options: + * - constants.RESTART_ON_REMOUNT — the saga will be started on component mount and + * cancelled with `task.cancel()` on component unmount for improved performance, + * - constants.ONCE_TILL_UNMOUNT — behaves like 'RESTART_ON_REMOUNT' but never runs it again. + * + */ +export default ({ key, saga, mode }) => WrappedComponent => { + class InjectSaga extends React.Component { + static WrappedComponent = WrappedComponent; + + static contextType = ReactReduxContext; + + static displayName = `withSaga(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`; + + constructor(props, context) { + super(props, context); + + this.injectors = getInjectors(context.store); + + this.injectors.injectSaga(key, { saga, mode }, this.props); + } + + componentWillUnmount() { + this.injectors.ejectSaga(key); + } + + render() { + return ; + } + } + + return hoistNonReactStatics(InjectSaga, WrappedComponent); +}; + +const useInjectSaga = ({ key, saga, mode }) => { + const context = React.useContext(ReactReduxContext); + React.useEffect(() => { + const injectors = getInjectors(context.store); + injectors.injectSaga(key, { saga, mode }); + + return () => { + injectors.ejectSaga(key); + }; + }, []); +}; + +export { useInjectSaga }; -- cgit v1.2.3