Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: How to export a method with a return value?

Tags:

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?

like image 986
Johannes Stein Avatar asked Apr 21 '15 11:04

Johannes Stein


People also ask

How do you return a function in react native?

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.

How do you get data from a function in React?

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.

How do I export a functional component in React?

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.


1 Answers

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);   } } 
like image 176
chrishale Avatar answered Sep 27 '22 20:09

chrishale