listening a NativeEventEmitter in useEffect -> Value not updating in useState hook

Viewed 18

I am trying to call a native module function on a react native button pressed. that function calls another native RCTDeviceEventEmitter function and emits an *textColor* event which captured in the javascript NativeEventEmitter. Each time the event is captured in listener I want to toggle a ncolor useState variable and change the ncolor between false and true. specified in the Text style property.

UseEffect listener -

const [ncolor, setnColor] = useState(false);
  useEffect(() => {
    const eventEmitter = new NativeEventEmitter(NativeModules.ToastExample);
    this.eventListener = eventEmitter.addListener('textColor', event => {
      console.log('event', ncolor, event); // "someValue"
      setnColor(!ncolor);
    });
    return () => {
      this.eventListener.remove(); //Removes the listener
    };
  }, []);

Native function module-

  @ReactMethod
    public void bangNotification(){
        Log.d("bang", "Bannnngg");
        notificationClick();
    }

Native function emitter -

public void notificationClick(){
        Log.d("bang", "Notification clicked");
        WritableMap map = Arguments.createMap();
        map.putString("val", "red");
        try{
            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("textColor", map);
        } catch (Exception e){
            Log.d("ReactNative", "Caught Exceptioin:" + e.getMessage());
        }
    }

The toggle behavior is only shown once after initialization. Why is it not setting new color value again and again?

Why do I have to specify the ncolor in [] in useEffect hook?

useEffect(() => {
    const eventEmitter = new NativeEventEmitter(NativeModules.ToastExample);
    this.eventListener = eventEmitter.addListener('textColor', event => {
      console.log('event', ncolor, event);
      setnColor(!ncolor);
    });
    return () => {
      this.eventListener.remove();
    };
  }, [ncolor]); //here

The listener keeps on listening as I can see the logs, but the state doesn't update. Why so??

0 Answers
Related