npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mqtt-react-hooks

v3.0.0-alpha.2

Published

ReactJS library for Pub/Sub communication with an MQTT broker using Hooks

Downloads

4,122

Readme

npm Quality and Build

Overview

This library is focused in help you to connect, publish and subscribe to a Message Queuing Telemetry Transport (MQTT) in ReactJS with the power of React Hooks.

Flow of Data

  1. WiFi or other mobile sensors publish data to an MQTT broker
  2. ReactJS subscribes to the MQTT broker and receives the data using MQTT.js
  3. React's state is updated and the data is passed down to stateless components

Key features

  • React Hooks;
  • Beautiful syntax;
  • Performance focused;

Installation

Just add mqtt-react-hooks to your project:

yarn add mqtt-react-hooks

Hooks availables

  • useMqttState -> return { connectionStatus, client, message }
  • useSubscription(topic: string | string[], options?: {} ) -> return { client, topic, message, connectionStatus }

Usage

Currently, mqtt-react-hooks exports one enhancers. Similarly to react-redux, you'll have to first wrap a root component with a Connector which will initialize the mqtt instance.

Root component

The only property for the connector is the connection information for mqtt.Client#connect

Example Root component:

import React from 'react';

import { Connector } from 'mqtt-react-hooks';
import Status from './Status';

export default function App() {
  return (
    <Connector brokerUrl="wss://test.mosquitto.org:1884">
      <Status />
    </Connector>
  );
}

Example Connection Status

import React from 'react';

import { useMqttState } from 'mqtt-react-hooks';

export default function Status() {
  /*
   * Status list
   * - Offline
   * - Connected
   * - Reconnecting
   * - Closed
   * - Error: printed in console too
   */
  const { connectionStatus } = useMqttState();

  return <h1>{`Status: ${connectionStatus}`}</h1>;
}

Subscribe

Example Posting Messages

MQTT Client is passed on useMqttState and can be used to publish messages via mqtt.Client#publish and don't need Subscribe

import React from 'react';
import { useMqttState } from 'mqtt-react-hooks';

export default function Status() {
  const { client } = useMqttState();

  function handleClick(message) {
    return client.publish('esp32/led', message);
  }

  return (
    <button type="button" onClick={() => handleClick('false')}>
      Disable led
    </button>
  );
}

Example Subscribing and Receiving messages

import React from 'react';

import { useSubscription } from 'mqtt-react-hooks';

export default function Status() {
  /* Message structure:
   *  topic: string
   *  message: string
   */
  const { message } = useSubscription([
    'room/esp32/testing',
    'room/esp32/light',
  ]);

  return (
    <>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <span>{`topic:${message.topic} - message: ${message.message}`}</span>
      </div>
    </>
  );
}

Tips

  1. If you need to change the format in which messages will be inserted in message useState, you can pass the option of parserMethod in the Connector:
import React, { useEffect, useState } from 'react';
import { Connector, useSubscription } from 'mqtt-react-hooks';

const Children = () => {
  const { message, connectionStatus } = useSubscription('esp32/testing/#');
  const [messages, setMessages] = useState < any > [];

  useEffect(() => {
    if (message) setMessages((msgs: any) => [...msgs, message]);
  }, [message]);

  return (
    <>
      <span>{connectionStatus}</span>
      <hr />
      <span>{JSON.stringify(messages)}</span>
    </>
  );
};

const App = () => {
  return (
    <Connector
      brokerUrl="wss://test.mosquitto.org:1884"
      parserMethod={msg => msg} // msg is Buffer
    >
      <Children />
    </Connector>
  );
};

Contributing

Thanks for being interested on making this package better. We encourage everyone to help improving this project with some new features, bug fixes and performance issues. Please take a little bit of your time to read our guides, so this process can be faster and easier.

License

MIT ©