4

I create a native module for android (in kotlin language)

class TestModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    override fun getName(): String {
        return "TestModule"
    }

    @ReactMethod
    fun testing(): String{
        return "my modules"
    }

}

I then registered this module in the ModulesPackages and add it to MainApplication.tk as instructed at https://facebook.github.io/react-native/docs/native-modules-android.html

in App.js

import {NativeModules} from 'react-native'
const TestingModule = NativeModules.TestModule;
type Props = {};
export default class App extends Component<Props> {
  render() {

    alert(TestingModule.testing());

    return (
      <View style={styles.container}>
        <Text style={styles.instructions}> test</Text>
      </View>

    );
  }
}

After running this, I expect to get the alert with the text "my modules", but I got alert with text "undefined"

I can't figure out what I did wrong. I did not see any error or complain when I run react-native run-android.

Any suggestion what I did wrong?

0

1 Answer 1

4

To make communication between native module and js module, you should invoke callback, promise or use event. In your case, the testing function could be change like

import com.facebook.react.bridge.Callback;

...

@ReactMethod
fun testing(callback: Callback): Void{
    callback.invoke("my modules")
}

Edit

you should pass a callback in js file in this case:

testCallback = (name) => {
    console.log(name);
}

componentDidMount() {
    TestingModule.testing(this.testCallback);
}
Sign up to request clarification or add additional context in comments.

4 Comments

it does not seems to work. Without changing the app.js, I got the error "...got 0 arguments, expected 1". If I put a variable, so I have alert(TestingModule.testing(testing)) , I got the error "The callback getCurrentAppState() exists in module AppState, but only one callback may be registered to a function in a native module" .
you must pass function to that native module when calling @Denvi, I've made an edit for my answer
Thanks, This works for the console. But is there anyway I can assigned that callback, naming "TestModule" string to a variable to display on the UI? Whatever I do, I can get that value on the console, but I do not know how to assign it to a variable for displaying on the UI
I believe, the : Void bit is wrong here (produces an error, see stackoverflow.com/q/44834965/3995261)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.