How to return Boolean from @ReactMethod to React Native?

I want to return Boolean from @ReactMethod to an actionNative Android app.

But when I do a method similar to

@ReactMethod public boolean retBoolean() { return true; } 

and call it from the JS component, it returns undefined. Only when the return type calls the void function, I cannot return a string or a boolean.

+7
android react-native
source share
2 answers

In accordance with the reaction documentation

To expose a JavaScript method, the Java method must be annotated using @ReactMethod. The return type of bridge methods is always invalid. React Native bridge is asynchronous, so the only way to pass JavaScript results is to use callbacks or emit events

So, if you want to return some value, like boolean or string, you need to use callbacks.

Example:

 @ReactMethod public void isEqual( int a, int b, Callback booleanCallback) { boolean equal= a == b; booleanCallback.invoke(equal); } 

In a javascript call as shown below ...

 YourClass.isEqual( 5, 10, (status) => { console.log('Result ',status); } ); 

For more information see this

+14
source share

Instead of using a callback, you can also use Promise .

 import com.facebook.react.bridge.Promise; @ReactMethod public void hasFlash(final Promise promise) { Camera camera = RCTCamera.getInstance().acquireCameraInstance(); if (null == camera) { promise.reject("No camera found."); return; } List<String> flashModes = camera.getParameters().getSupportedFlashModes(); promise.resolve(null != flashModes && !flashModes.isEmpty()); } 

Then in your JS call it with

 const myFunction = async () => { const hasFlash = await CameraManager.hasFlash(); } 
+7
source share

All Articles