syarul
syarul

Reputation: 2187

How to write a simple react-native native module with a callback

How to get this work, in the simplest way, I have trouble getting the callback send to react-native, probably I'm missing something.

@ReactMethod
public void testCallback(Callback cb) {

String sampleText = "Java is fun";
int textLength = sampleText.length();
    try{
        cb.invoke(textLength);
    }catch (Exception e){
        cb.invoke("err");
    }
}

On react-native side

var getNativeCallback = require('react-native-native-callback');


getNativeCallback.testCallback(function (result){
    console.log(result)
})

Upvotes: 8

Views: 8347

Answers (1)

Juanan Jimenez
Juanan Jimenez

Reputation: 224

I have to face the same problem, and finally I have to take a different approach, as apparently, there is no Callback type accepted for @ReactProp.

Instead I used the 'Events' way, in order to have response communication from Android native to React Native.

In the Android side I set up a SendEvent function conveniently fired as it needs:

private void sendEventToReactFromAndroid(ReactContext reactContext,String eventName, @Nullable WritableMap params) {
    reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}

@Override
public void customAndroidListenerFunction() {
    sendEvent(mcontext, "EventName", null);

}

Then in the React side, you will expect this event, and parameters if you may like:

var {DeviceEventEmitter} = require('react-native');
...
componentWillMount: function() {
    DeviceEventEmitter.addListener('EventName', function(e: Event) {
        console.log("Received event loud and clear in the React Native side!");
    });
},
...

Hope that helps.

Upvotes: 3

Related Questions