androidreact-nativenative-module

How to add default value of Native Bridge Android in React Native


I have some service that need to start repeatedly by user input or given default value, so i need to add parameter to handle it,

I have tried this:

@ReactMethod
public void start(){
  start(1000);
}

@ReactMethod
public void start(int timer){
  Intent i = new Intent(reactContext, ServiceUploadData.class);
  i.putExtra("Interval", timer);
  reactContext.startService(i);
}

but those code show an error

start got 0 arguments, expected 1

anyone can help me?


Solution

  • Although I haven’t seen it in the docs I have seen this in the code

    We do not support method overloading since js sees a function as an object regardless of number of params.

    https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java

    To get around this issue you could do one of the following.

    1. Change the name of public void start(), perhaps to public void startWithDefault()
    2. Expose only public void start(int timer) and handle the initial value on the JavaScript side
    3. Expose both functions (with different names) but then wrap them in a JavaScript function that uses an if to check an initial value has been set and then call the appropriate function.

    The second and third option allow you to keep your api the same to the user as they will only ever be interacting with the JavaScript.