0

Hello friends i want to make my plugin in react native and i want to call my ios native module function from my react native js file so below is my code

ios library code as below

@implementation RNMyLib

- (dispatch_queue_t)methodQueue{
   return dispatch_get_main_queue();
 }
RCT_EXPORT_MODULE()


 RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback)
 {
    NSString * strName = @"findEvents";

   callback(strName);
}

JS file code as below

 import { NativeModules } from 'react-native';

 var MyLibManager = NativeModules.RNMyLib;

 MyLibManager.findEvents((strName) => {
    console.log("GET FUN CODE >>>>> "+ strName);
 });

i want to just call simple function from my js file to ios native library class but when i run above code i get error like TypeError: undefined is not an object (evaluating 'MyLibManager.findEvents')

any idea how can i solve this ? your all suggestions are applicable

Harshal Kalavadiya
  • 2,412
  • 4
  • 38
  • 71

1 Answers1

0

So in your native code you actually have to pass an NSArray back to the callback. Kind of like this.

RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback)
{
  NSArray *events = ...
  callback(@[[NSNull null], events]);
}

The first element in the NSArray is your chance to pass an error. In your case it always resolves so just keep it an [NSNull null]. The second argument instead of events in the example would be your strName.

From the JS side the callback actually is a traditional node callback which takes an error as the first argument and the actual item resolved in the second argument. So instead,

MyLibManager.findEvents((_, strName) => {
    console.log("GET FUN CODE >>>>> "+ strName);
})

If you like the promise pattern better you may use the following:

RCT_REMAP_METHOD(findEvents,
                 findEventsWithResolver:(RCTPromiseResolveBlock)resolve
                 _:(RCTPromiseRejectBlock)reject) // I like to leave this as _ if it never fails
{
  NSString *strName = @"findEvents";
  resolve(strName);
}

And from JS.

const strName = await MyLibManager.findEvents;