Exposing our native module to javascript
We have now created all the native code to expose new functionality to our JavaScript code, so it should only be a matter of calling it, right? Well, yes...... but we are going to be a little smarter about it. Just because the native code has been created does not mean our code is type-safe by default - remember, the bridge simply serializes/deserializes everything into JSON.
So we are going to create a small wrapper for our native code, create a BuildingAppsNative.ts
file inside of a new libs
folder:

import { NativeModules } from "react-native";
interface IBuildingAppsNative {
keychainWrite: (key: string, payload: string) => Promise<boolean>;
keychainRead: (key: string) => Promise<string>;
}
function createBuildingAppsNative(nativeModule: any): IBuildingAppsNative {
return {
keychainRead: nativeModule.keychainRead,
keychainWrite: nativeModule.keychainWrite
}
}
export const buildingAppsNative = createBuildingAppsNative(
NativeModules.BuildingAppsNative
)
Basically, React Native exposes our created module inside of the NativeModules
. We are just going to provide a type-safe wrapper. Here you could also disable the methods if you have certain specific functionality that won't work on other platforms (iOS or android).
import { Platform } from 'react-native';
keychainRead: Platform.OS === 'macos'? nativeModule.keychainRead : () => null,
After we have created our wrapper we can use it. Since we are interested in saving our state, we are going to enhance our UI store a bit, so after importing our native module, we will add a couple of functions:
import { buildingAppsNative } from "libs/BuildingAppsNative";
This page is a preview of Building React Native Apps for Mac