What is the best way to export a method with a return value in React Native?
I know there is RCT_EXPORT_METHOD
, but that only works for methods that are (void)
and therefore don't return anything. Preferably I don't need to export the whole class, just a few methods.
The other option would be to have a callback, but I would like to avoid that if possible as it bloats up the code too much in my use case. Are there are any other options I might have missed?
To use string from function in react native, just use the like ${function()}/hello syntax to call a function and concat in a string. Like the following example, we can create a function that return a string and uses a function in a react native render function.
The most accessible way to fetch data with React is using the Fetch API. The Fetch API is a tool that's built into most modern browsers on the window object ( window. fetch ) and enables us to make HTTP requests very easily using JavaScript promises.
Use named exports to export a component in React, e.g. export function Button() {} . The exported component can be imported by using a named import as import {Button} from './another-file. js' . You can use as many named exports as necessary in a file.
You can also now use promises, which tend to look a little nicer in your JS.
Objective C:
RCT_REMAP_METHOD(getThing, resolver: (RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { if( condition ) { NSString *thingToReturn = @"ALL OK"; resolve(thingToReturn); } else { reject([NSError errorWithDomain:@"com.companyname.app" code:0 userInfo:@{ @"text": @"something happend" }]); } }
Then in JS:
async onPress() { try { const status = await CustomModule.getThing(); // do something with status } catch(e) { console.error(e); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With