Expo React Native with IoT Hub

Alex Fang 230 Reputation points
2023-07-17T22:23:12.7566667+00:00

Does anyone perhaps have a sample React Native app that interacts with Azure IoT Hub?

All of the projects and samples that I am finding online have the frontend written using HTML for web applications and not in JS or JSX. I am not sure if this affects how I am supposed to create my React Native application and I can't find any projects that don't use pure HTML.

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,272 questions
0 comments No comments
{count} votes

Accepted answer
  1. LeelaRajeshSayana-MSFT 17,766 Reputation points Moderator
    2023-07-18T22:04:58.39+00:00

    Hi @Alex Fang Greetings! Thank you for posting this question. You would not be able to utilize Azure IoT SDK with React Native directly as the SDK is not compatible. You can implement the SDK in Node.js and expose Rest API endpoints to call them from React Native Application. Please find the below example which demonstrates this implementation.

    Node.js implementation of Get Digital Twin service SDK and exposing the API

    const express = require('express');
    const IoTHubTokenCredentials = require('azure-iothub').IoTHubTokenCredentials;
    const DigitalTwinClient = require('azure-iothub').DigitalTwinClient;
    const { inspect } = require('util');
    
    async function main() {
        const deviceId = "TestDevice4";
        const connectionString = "<IoTHubConnectionString>";
    
        // Create digital twin client
        const credentials = new IoTHubTokenCredentials(connectionString);
        const digitalTwinClient = new DigitalTwinClient(credentials);
    
        // Get digital twin and retrieve the modelId from it
        const digitalTwin = await digitalTwinClient.getDigitalTwin(deviceId);
    
        //console.log(inspect(digitalTwin));
        delete digitalTwin._response.parsedBody
        const jsonData = JSON.stringify(digitalTwin);
        console.log('Json data '+jsonData);
    
        console.log('Model Id: ' + inspect(digitalTwin.$metadata.$model));
    
        return jsonData;
    }
    
    
    const app = express();
    app.use(express.json());
    const PORT = 3000;
    app.listen(PORT, () => {
        console.log("Server Listening on PORT:", PORT);
        app.get("/status", (request, response) => {
            var status = {
                "Status": "Running"
            };
            main().then((twindata) => {            
                status = JSON.parse(twindata);
                var responseBody = status._response.bodyAsText
                //console.log('Body as Text prop value '+responseBody)
                //delete status._response.parsedBody;
                response.send(responseBody);
            }).catch((err) => {
                console.log('error code: ', err.code);
                console.log('error message: ', err.message);
                console.log('error stack: ', err.stack);
                status = {
                    "Status": err.message
                };
                response.send(status);
            });
    
            
        });
    });
    
    
    

    Please note to provide the correct connectionString to point to you IoT Hub. In the above code, I am trying to extract a particle section of the Digital Twin using the line var responseBody = status._response.bodyAsText. You would want to modify this and expose the desired data through the Endpoint.

    React Native Expo application to invoke the API

    import { StatusBar } from 'expo-status-bar';
    import React, { useState, useEffect } from 'react';
    import { StyleSheet, Text, View } from 'react-native';
    
    
    
    export default function App() {
      
      const [jsonData, setJsonData] = useState({});
    
      const fetchTwin = async () => {
        try {
          const response = await fetch('http://10.0.0.102:3000/status');      
          const data = await response.json();      
          setJsonData(data);
        }
        catch (error) {
          console.error('Error fetching data: ' + error)
        }
      };
    
      useEffect(() => {
        fetchTwin();
      }, []);
    
    
      return (
        <View style={styles.container}>
          <Text>Using Azure IoT Hub Service SDK!</Text>
          <Text>Last reboot time: {JSON.stringify(jsonData.iothubDM.reboot.lastReboot)} </Text>
          <StatusBar style="auto" />
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      },
    });
    
    
    

    Note that I have extracted a specific part of my returned data and returned it to the view. Please refer the below image showing the data when I viewed it through Android Expo Go application

    enter image description here

    Hope this helps! You might also consider to use Azure IoT Rest API end point and call it using the React native fetch method instead of implementing and exposing the Service SDK.


    If the response helped, please do click Accept Answer and Yes for the answer provided. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.