I have come across a very weird problem. I have a function that is being used as a callback for an eventListener. This callback has a setState call inside it.
The weird thing is that if I pass the function as a prop to another component and call it in the onClick handler, the setState call executes and its callback prints to the console.
When I'm using it as the callback to the eventListener, on the event being fired, the function is running, but the setState inside it does not run!
No error or warning is thrown on the console.
Code:
Utils.js
import { EventEmitter } from 'fbemitter';
const emitter = new EventEmitter();
CurrentFile.jsx
import { emitter } from './Utils';
class ComponentWithListener extends React.Component {
state = {
selections: this.props.selections
};
componentDidMount() {
emitter.addListener('resetSelections', () => this.resetSelections());
}
componentWillUnMount() {
emitter.removeAllListeners('resetSelections');
}
resetSelections = () => {
console.log('resetSelections() called');
this.setState({ selections: this.props.initialSelections }, () => {
console.log('successfully reset selections');
someFunctionCall();
});
}
}
OtherFile.jsx
import { emitter } from './Utils';
class OtherFile extends React.Component {
// ..state declaration and other functions
resetStoredFilters = () => {
// do some things
emitter.emit('resetSelections');
}
// other functions and render()
}
So here, whenever resetStoredFilter() is run, the setState inside resetSelections() is not run, and the output I get on console for resetSelections() is:
resetSelections() called
someFunctionCall() runs.
Compare this to when I pass resetSelections as a prop to a child component and call it from inside an onClick handler from inside the child component:
// body of some function inside child component
onClick={resetSelections}
When this element is clicked inside the child component, the output I get on the console for resetSelection() is:
resetSelections() called
successfully reset selections
someFunctionCall() does not run.
I even tried using functional components and useState hook in CurrentFile.jsx to check if that makes a difference. I see the same issue still.
Why does this happen? And how to make the setState run in eventListener callbacks?