swiftreact-nativebridging-header

How to Pass Data from function/Custom Hooks in React-Native to Swift?


I'm planning to pass data from React-Native to Swift. The method of sending data can be an hook or a function. After reading the doc I only found the option to pass component to the Swift View which is not helpful in my case. The data can be of any type. I have given a sample hook and a function below. Please let me know the best approach.

I have tried using module.exports and requireNativeComponent it didn't work out.

Thanks in Advance

useFetchData.ts

import {useEffect, useState} from 'react';
import axios from 'axios';

const useFetchData = () => {
  const [data, setData] = useState({});

  useEffect(() => {
    const fetchData = async () => {
      try {
        const {data: response} = await axios.get(
          'https://hn.algolia.com/api/v1/search?query=redux',
        );
        setData(response);
      } catch (error) {
        console.error(error);
      }
    };

    fetchData();
  }, []);

  return {data};
};

export default useFetchData;

FunctionExample.ts

const sampleFunction = () => {
   return "This is Sample Data"
}

I also have the bridge set up in Obj-C for RCT_CUSTOM_VIEW_PROPERTY

#import <Foundation/Foundation.h>
#import "ReactImports.h"
#import <React/RCTView.h>


@implementation ReactImports

RCT_EXPORT_MODULE()

- (UIView *)view
{
    return [[UIView alloc] init];
}

RCT_CUSTOM_VIEW_PROPERTY(reactNativePropString, NSString, UIView)
{
    view.accessibilityLabel = json ? [RCTConvert NSString:json] : defaultView.accessibilityLabel;
}
@end


Solution

  • You can create a native module and expose functions to react native. On RN side, you call the function passing the values that you want.

    https://reactnative.dev/docs/native-modules-intro

    If you're having trouble, send me a message on linkedin and I'll try to help you.