'pass dispatch function to another instance property as callback to execute later on
Sorry for pseudo-code. Think that the problem can be understood like so. Working in a reproducible example.
Consider the following pseudo code:
Class foo:
let fooInstance = null
class Foo() {
constructor(){
fooInstance = this;
this.fooCallback = null // property to assign callback
}
static getInstance() {
return fooInstance
}
callbackExecutor() {
if (this.fooCallback) // callback always null here even the assignment is ok in the component
this.fooCallback();
}
}
React-redux component:
import { argumentFunc } from 'src/argumentFunc'
class MyComponent extends Component {
constructor(props) {
...
}
componentDidUpdate(prevProps, prevState) {
const foo = Foo.getInstance()
if (whateverCond) {
// callback assignment to instance. this.props.argumentFunc() works if called here
foo.fooCallback = this.props.argumentFunc();
}
}
}
...
const mapDispatchToProps = (dispatch) => ({
argumentFunc: () => dispatch(argumentFunc()),
})
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
I assign the callback to the instance, but then in the callbackExecutor, this.fooCallback is null.
I tried:foo = this.props.argumentFunc();foo = this.props.argumentFunc;foo = () => this.props.argumentFunc();foo = () => this.props.argumentFunc;
How can I pass a callback to the instance (fooInstance) to be called later on within the class instance methods(callbackExecutor())?
Solution 1:[1]
Have you tried:
foo.getInstance().fooCallback = this.props.argumentFunc.bind(this)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Konrad Linkowski |
