Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native : Native modules return nothing

I'm new to React Native and I want to call native modules to get some strings from Android . I write the code like this:

@ReactMethod
public String getToken() {
    String token = "";
    //then take the token
    Log.i("getToken:", token);
    return token;
}

Then use in js.

var tokenString = thismodule.getToken();

However ,when i call the method in js. I can see the correct log " I/getToken : palapalapala " in logcat , but js can't get anything.

So , what's the correct code of this?

like image 647
Luo Ruidong Avatar asked Oct 21 '25 11:10

Luo Ruidong


2 Answers

Oh,yes . I should know . The communicate between js and native is asynchronous . The js method who bridge to the native method , can't return anything now . So , we must sent a callback function to native and get the correct answer in the callback.

That's all.

like image 66
Luo Ruidong Avatar answered Oct 23 '25 00:10

Luo Ruidong


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

@ReactMethod
public void getToken(Callback callback) {
    String token = "";
    //then take the token
    Log.i("getToken:", token);
    callback.invoke(token);
}

thismodule.getToken((token) => {
  console.log('Result ',token);
 }
);
like image 20
Akshay I Avatar answered Oct 23 '25 00:10

Akshay I



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!