Search code examples
javaandroidreact-nativeapi-designduck-typing

Type checking on React Native plugin


We have a React Native plugin that bridges a native library both on iOS and Android. This week a client reported he was having issues using it, the method is as follows (Android)

@ReactMethod
public void setUser(String id){
    Core.INSTANCE.setTag("uid", id);
}

The issue we faced is the client used this method on the js side this way:

Library.setUser(3321) // Number instead of string

Apparently, he did not get any errors on the JS side; it just ignored this line. My question would be, can I type-check on the JS side so the client gets an error or could I, in a duck typing way, accept anything on the JS side and then call .toString() or String(x)?

I want the client to either know he has to fix the issue or for the method to be able to "just work" with anything.


Solution

  • I would suggest you create a js layer as well and ship both native and js together. In the js module, you can handle this call any way you want. You can type-check there and show the warning, or convert to string.

    Another option would be to pass as a parameter not a number but an object. Then in Java, you will receive a ReadableMap which makes the conversion much easier.