I don't know why when I fire an event the DeviceEventEmitter.addListener it's been emit once but listening twice.
I have a component Base that it's been add in every screen, something like
<View>
{this.props.children}
<ModalComponent />
</View>
Where the ModalComponent should be able to open anytime that ModalVisible event it's fired.
constructor (props) {
super(props)
this.state = {
modalVisible: false
}
}
componentDidMount() {
DeviceEventEmitter.addListener('ModalVisible', this.onModalVisible)
}
componentWillUnmount () {
DeviceEventEmitter.removeListener('ModalVisible', this.onModalVisible)
}
onModalVisible = (args) => {
console.log(['ModalVisible', args]) // logging twice
this.setState({
modalVisible: args.visible
})
}
close () {
this.setState({
modalVisible: false
})
}
onRequestClose = () => {
this.close()
}
render() {
return (
<Modal animationType={'slide'} transparent={false} visible={this.state.modalVisible} onRequestClose={this.onRequestClose}>
...
</Modal>
)
}
And I have a Server the emits the event when needed
static show (data) {
console.log(['Service.show', data]) // only once
DeviceEventEmitter.emit('ModalVisible', { visible: true })
}
When Service.show it's called, the first log appears only once, but right away at the addListener it's been logged twice.
I've already tried
this.listener = DeviceEventEmitter.addListener(...)
this.listener.remove()
and
this.onModalVisible.bind(this)
But it gave me every the same problem.
Besides that, at the same moment the Modal it's been duplicated, where when I close, I have two modals to be close.
I also tried load all this in a new screen, without parents components, to see if that could be the problem, mas no. It still.
I had the same problems with events being fired/registered twice with socket.io, my problem was due to the fact that I was adding eventListeners on DidMount method. But since my component was mounted multiple it was also adding eventListeners multiple times.
My guess is that you are using the same component multiple times and so adding multiple times the same eventListener. Try to add your eventsListener into another place that will be called only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With