Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a Boolean from @ReactMethod in React Native?

I want to return a Boolean from @ReactMethod in reactNative Android application.

But when I make method similar to

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

and call it from JS component ,it returns undefined. only when return type is void function gets called ,I am not able to return string or boolean.

like image 521
stack Learner Avatar asked May 16 '16 11:05

stack Learner


2 Answers

Rather than using callback, you could 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(); 
}
like image 156
Michael T. Avatar answered Sep 19 '22 09:09

Michael T.


According to react documentation

To expose a method to JavaScript a Java method must be annotated using @ReactMethod. The return type of bridge methods is always void. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting 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 javascript call like below...

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

For more info refer this

like image 38
Jickson Avatar answered Sep 20 '22 09:09

Jickson