Today I Learned

A Hashrocket project

Export a synchronous method in React Native module

If you are working with an existing brownfield iOS app you may already have some code that is really complicated to change and sometimes you want a bridge module to export some native methods to JS that return synchronous values right way. In iOS, you can use the macro RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD:

@define API_URL @"http://localhost:3000"

@implementation ConfigManager

RCT_EXPORT_MODULE();

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getApiUrl) {
  return API_URL;
}

@end

And in your JS file you can call:

import { NativeModules } from 'react-native';

const apiUrl = NativeModules.ConfigManager.getApiUrl();

There is a problem using that when your app is in debug mode. It will raise the error global.nativeCallSyncHook is not a function. Also this macro blocks the current thread, so only use it if you REALLY need it.