With DOM, you can easily create a trigger custom event with Javascript like so:
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);
// Dispatch the event.
elem.dispatchEvent(event);
Is there a way to do that with React-Native?
With DOM, you can easily create a trigger custom event with Javascript like so:
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);
// Dispatch the event.
elem.dispatchEvent(event);
Is there a way to do that with React-Native?
Share Improve this question edited Dec 21, 2022 at 23:30 Monero Jeanniton asked Sep 25, 2018 at 15:30 Monero JeannitonMonero Jeanniton 49910 silver badges26 bronze badges 7- 4 You could try this library. It might help. – Christopher Bradshaw Commented Sep 25, 2018 at 15:51
- What are you trying to achieve with the events? – JRK Commented Sep 25, 2018 at 16:19
- thanks for your suggestion I will try it and let you know @ChristopherBradshaw – Monero Jeanniton Commented Sep 25, 2018 at 16:54
-
@JRK I have create a wrapper for
AsynchStorage
calleddeviceStorage
where, in my dictionary application, user can add word to favorite list/array saved in thedeviceStorage
with a specific key. I want to know whenever a new word as been added to thefavorites
list so I can reflect this update to the home which is actually previous screen of the application.ponentDidMount
won't work since the home page has already been mounted (still in screen stack). PS: the screen where you actually add a new word in favorite list, is pushed from the home screen. Won't mind sharing u code. Thx – Monero Jeanniton Commented Sep 25, 2018 at 17:07 - 1 @Monero Did you find solution to this ? – Pranjal Gore Commented Dec 10, 2019 at 10:20
2 Answers
Reset to default 7React Native provides NativeEventEmitter
for handling custom events.
import { NativeEventEmitter } from 'react-native';
const eventEmitter = new NativeEventEmitter();
eventEmitter.emit('custom-event', { data: 'test' });
eventEmitter.addListener('custom-event', event => {
console.log(event); // { data: 'test' }
});
There are actually two solutions for my case:
- https://reactnavigation/docs/en/function-after-focusing-screen.html
Use react-navigation to know when the ponent/screen has received focus and trigger an action with a 'didFocus' event listener:
import React, { Component } from 'react';
import { View } from 'react-native';
import { withNavigation } from 'react-navigation';
class TabScreen extends Component {
ponentDidMount() {
const { navigation } = this.props;
this.focusListener = navigation.addListener('didFocus', () => {
// The screen is focused
// Call any action
});
}
ponentWillUnmount() {
// Remove the event listener
this.focusListener.remove();
}
render() {
return <View />;
}
}
export default withNavigation(TabScreen);
- https://redux.js/basics/example
Use Redux as one global state container for your application.