I have a helper function which is utilized by two components in my React app. And this helper function dispatches a set of Redux actions. How do I connect React-Redux to this helper function so that it can dispatch actions?
My helper looks like this:
export default const helper = () => {
//dispatch some actions
// I would like to do something similar to this: this.props.dispatch()
//do something else(produce some JSX)
}
My component look like this:
import helper from './helper.js';
export default class Example extends React.Component {
return (
{helper()}
);
}
My component 1 look like this when the helper is defined inside the component itself:
import { setTime } from '../actions/setTime.js';
class Example1 extends React.Component {
helper() {
//actions are synchronous
this.props.setTime('10:00PM');
return (<h1>hello</h1>);
}
render() {
return (
<h1>something</h1>
{helper()}
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
setTime: (time) => (dispatch(setTime(time)))
};
}
export default connect(null, mapDispatchToProps)(Example1);
My component 2 look like this when the helper is defined inside the component itself:
import { setTime } from '../actions/setTime.js';
class Example2 extends React.Component {
helper() {
//actions are synchronous
this.props.setTime('10:00PM');
return (<h1>hello</h1>);
}
render() {
return (
{helper()}
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
setTime: (time) => (dispatch(setTime(time)))
};
}
export default connect(null, mapDispatchToProps)(Example2);
Example1 and Example2 renders based on Route change. You might be thinking I can use the higher order component but I cannot because these two components have different state and renders different things.
Please note that I want to have access to the dispatch function in the helper method and I am not accessing Redux state from that component so I do not have to worry about state change(mapStateToProps is not in use).
connect( mapStateToProps, mapDispatchToProps )( Component )you are asking?dispatchto your helper method? You really don't want to dispatch some actions from your rendering method, as it could change the state of your component and create some kind of continuous / endless render -> dispatch -> state update -> render -> dispatch ... If you wish to create jsx based on a certain state, maybe your helper should do only that, and you can pass the current state in?connect, I think that would be the most easy way to do it, your helper function would then get dispatch as a first argument (but then you could dispatch from inside your component instead)