When you see the error message “invariant violation: ‘new NativeEventEmitter()’ requires a non-null argument,” it means that you are trying to instantiate a NativeEventEmitter object without providing a valid argument. The NativeEventEmitter is a class provided by React Native for handling native events.
The error typically occurs when you forget to pass the necessary argument to the NativeEventEmitter constructor. The argument should be an instance of the NativeModules, which is a bridge between JavaScript and Native modules in React Native.
Example:
import { NativeEventEmitter, NativeModules } from 'react-native';
// Create an instance of NativeEventEmitter using NativeModules as an argument
const eventEmitter = new NativeEventEmitter(NativeModules);
// Register an event listener
const subscription = eventEmitter.addListener('eventName', (data) => {
// Handle the event data
});
// Remove the listener when no longer needed
subscription.remove();
In the above example, we import both NativeEventEmitter and NativeModules from the ‘react-native’ package. The NativeModules is used as an argument to create an instance of NativeEventEmitter. This ensures that a valid argument is passed to the constructor, preventing the “invariant violation” error.