Event Listener In React Native – Sending And Receiving Events Across Different Files

Recently I came across a case where I wanted to call 2nd API in file A once 1st API is called in file B. Here A file should know when 1st  API is called from file B. To achieve this communication between two files I used react-native-event-listeners. This library helped me in sending and receiving events across different files. Every event which occurs in React Native is either user or API generated.

React Native is a programming framework that uses a universal programming language called JavaScript. React Native gives developers the ability to develop full, native mobile applications for both Android and iOS. The main benefit of applying React Native is that developers won’t have to build the same Android and iOS. Instead, developers can again use the same coding across each platform, and it takes a shorter development time.

Event Listener is an important part of JavaScript where UI responds according to an event that occurs. Event listeners wait for an event to occur and pass that event across different files. It helps us to add interactive functionality to our react native app by listening to the events.

Let’s see an example of Event Listener in React Native hooks.

Installations:

npm install --save react-native-event-listeners

For ios,

cd ios && pod install

Import library in both the files A and B,

Import EventRegister from react-native-event-listeners. Add emit configs in any one of the files. I will export it in file A. You can have multiple configs for different events.

Import emitConfig in file B,

Let’s say we have called 1st API in file B using fetch. Fetching resources across the network are provided by fetch API. Fetch provides request and response objects. Once we get the success response we will emit the event like below,

Here with emit we are sending events using the emit method. Where the 1st param is eventName and the second one is data or message which we want to pass. Request to do something is known as emitting the event.

Syntax:

emit(eventName, data)

Now let’s switch to file A to receive the event and call 2nd API. To receive an event we will use the addEventListener() method inside useEffect to call it as soon as possible.

Syntax:

addEventListener(eventName, callBack)

As soon as we receive the event we will call the 2nd API inside the callBack. Once the event is used we will remove it using removeEventListener method. Waiting for an event or events to be processed is known as a subscriber.

coma

Conclusion

Using event listener in react native we have achieved communication between two files for sending and receiving events successfully. I hope this article will help you in various ways to handle events that may be user-generated or API generated.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?