A powerful React library for simplify MQTT integration
Report Bug .
Request Feature
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.
Follow the documentation for detailed instructions on implementing this features."
npm install mqtt-react-hook
#or
yarn add mqtt-react-hook
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
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.
brokerUrl: string
opts: string
manualConnect: boolean
true
if you don't want your MQTT client to connect automatically after the initial render of your
application. In this case, you must call the reconnect
function manually whenever you want to connect to the
MQTT broker. This option is useful when certain client options, such as credentials, are not yet ready during the
initial render of your application.false
mqtt: MqttClient | null
status: "online" | "offline" | "reconnecting" | "error"
reconnect: (url?: string, opts?: Omit<IClientOptions, "manualConnect">) => Promise<MqttClient | null>
useMqttSubscribe
A hook for subscribing into a topic.
pattern: string
eg: device/+id
params: Record<string, string>
Optional
The dynamic params which exist on topic pattern.
For example, if your topic pattern is device/+id/+name
, you must provide the following parameters
to useMqttSubscribe
to create your topic.
{id: "123", name: "sampleName"}
This library uses mqtt-pattern
to create topics. The topics are generated based on the pattern and params values
passed as arguments.
options: IClientSubscribeOptions
onSubscribeSuccess: (granted?: ISubscriptionGrant[]) => void
onSubscribeError: (e: Error) => void
onMessage: (payload: any) => void
onUnSubscribe?: (error?: Error, packet?: Packet) => void
unSubscribeOptions: IClientSubscribeOptions
enable: boolean
false
to disable this subscription from automatically subscribed.true
cacheFirst?: boolean
false
payload: any
subscribe: () => TSubscribeReturnType
unSubscribe: () => void
isReady: boolean
params
have value, and the hook has successfully created the topic from the pattern.isEnable
is true, the hook will subscribe to the topic when isReady
becomes true.status: "subscribed" | "unSubscribed" | "idle" | "error"
idle
: when any of mqtt.connected
, isEnable
, or isReady
is false
.subscribed
: hook successfully subscribed to topicunSubscribed
: When the hook has been unsubscribed from the provided topic. the action of unsubscription will
occur in the following scenarios:
unsubscribe
function returned by hook, will be called method.unSubscribeTopic
method in the useMqttUtils
hook, it changes the status of
all subscription hooks for the provided topic to unSubscribed
.error
: If there are any errors in the subscription, the corresponding error property contains the error
received.errors: unknown[]
:
topic: string | null
:
pattern
and params
.id: string
dataUpdatedAt: Date | null
useMqttPublish
A hook for publishing a message (payload) into a topic.
pattern: string
eg: device/+id
params: Record<string, string>
device/+id/+name
, you must provide the following parameters
to useMqttPublish
to create your topic.{id: "123", name: "sampleName"}
mqtt-pattern
to create topics. The topics are generated based on the pattern and params values
passed as arguments.isReady: boolean
params
have value, and the hook has successfully created the topic from the
pattern.publish: (config: TPublishmentConfig) => Promise<Packet | undefined>;
isReady
is true.the config
params can have the following values
payload: any
options: IClientPublishOptions
onPublishSuccess: (packet?: Packet) => void
onPublishError: (e: Error) => void
status: "publishing" | "published" | "error" | "idle"
idle
: when the publish
method has not been called yet.published
: When the hook successfully publishes the message to the topic.publishing
: When the hook is attempting to publish the message.error
: If there is an error in publishment, the corresponding error property contains the error received.errors: unknown[]
topic: string | null
pattern
and params
.useMqttUtils
A hook that returns several useful utilities.
unSubscribeTopic: ({ topic: string, options?: IClientSubscribeOptions }) => void
unSubscribed
when:
unSubscribe
function returned from useMqttSubscription
is called.unSubscribeTopic
function is called, it will unsubscribe all subscriptions to the provided topic. getCache: (topic: string, buffer?: boolean) => undefined | TCacheItem
type TCacheItem = { time: Date payload: ArrayBuffer | object topic: string }
topic
buffer
Determines whether you want to receive the raw message (Buffer) or the converted version (Object).deleteCache: (topic: string) => void
clearCache: (topic: string) => void
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.
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.
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!
git checkout -b feature/AmazingFeature
)git commit -m 'Add some AmazingFeature'
)git push origin feature/AmazingFeature
)Distributed under the MIT License. See MIT License for more information.
Sina Sadjadi - linkedin - sinasadjadi@proton.me
Project Link: https://github.com/sinasadjadi/mqtt-react-hook