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.
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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With