sinasadjadi / mqtt-react-hook

MIT License
4 stars 1 forks source link


Mqtt React Hook

React + MQTT

A powerful React library for simplify MQTT integration



Report Bug . Request Feature




About The Project

If you have experience developing MQTT functionality within a React application, you may have encountered challenges when managing a growing number of topics. As the number of topics increases, it becomes difficult to handle them effectively.

mqtt-react-hook is a React library that offers multiple React hooks, designed to simplify the integration of MQTT functionality within your React applications.

Features

Follow the documentation for detailed instructions on implementing this features."

Installation

   npm install mqtt-react-hook
   #or
   yarn add mqtt-react-hook

Usage

1- To begin, ensure your main parent component are wrapped within the ReactMqttContextProvider context provider. This enables each child component within it to access the provided hooks.

import {ReactMqttContextProvider} from "mqtt-react-hook";

const App = () => {

    return (
        <ReactMqttContextProvider
            brokerUrl={"BROKER_URL"} //mqtt broker url 
        >
            //your components
        </ReactMqttContextProvider>
    )
}
export default App

2- use the hooks: useMqttSubscribe , useMqttPublish

import {useMqttSubscribe, useMqttPublish} from "mqtt-react-hook";

const UserInfo = () => {

    const USERID = "46ead19a-98da-4790-9eac-73e5aa3f3e70"

    // to subscribe to a topic
    const {payload: user} = useMqttSubscribe({
        pattern: "USER_INFIO/+userId",
        params: {userId: USERID},
    })

    // to publish a topic
    const publishment = useMqttPublish({
        pattern: "GET_USER_INFO",
    })

    const getUserData = async () => {
        await publishment.publish({payload: {userId: USERID}})
        console.log("published")
    }

    return (
        <div>
            <button onClick={getUserData}>get user info</button>
            {Boolean(user.id) && (<div>{user.name}</div>)}
        </div>
    )
}

export default UserInfo

API Reference

ReactMqttContextProvider

A Context Provider is utilized to instantiate and initialize the MQTT instance object. Wrapping your main component within this Context Provider is necessary to access the provided hooks.

available props:

returns:

useMqttSubscribe

A hook for subscribing into a topic.

available props:

returns:

useMqttPublish

A hook for publishing a message (payload) into a topic.

available props:

returns:

useMqttUtils

A hook that returns several useful utilities.

returns:

TypeScript

mqtt-react-hook includes embedded type definitions to enhance your IDE experience and prevent errors like type coercion.

This is an optional feature that may impact compilation time depending on your project size. However, it's highly recommended for developers using TypeScript to take advantage of the type enhancements it offers.

Create a declaration file and export it

You can define your own types for topics using Type Augmentation and Merging Interfaces in TypeScript. To begin, create a declaration file that exports a module named mqtt-react-hook.

export declare module "mqtt-react-hook" {
    interface IPattern {
        "GET_DEVICE_INFO/+userId/+deviceId": {
            // define the param types
            params: { userId: string, deviceId: string }

            // Define the payload type.
            // In subscription, it is the expected received payload
            // In publications, it is the payload that must be published as a message.
            payload: { deviceId: string, version: number, isWork?: boolean }[]
        }
    }
}

Easy-peasy, that's it.

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the MIT License. See MIT License for more information.

Contact

Sina Sadjadi - linkedin - sinasadjadi@proton.me

Project Link: https://github.com/sinasadjadi/mqtt-react-hook

Acknowledgments