Git Product home page Git Product logo

rc-mqtt's Introduction

NPM version NPM Downloads jsDelivr Downloads License

rc-mqtt

中文说明

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

Installation

Just add rc-mqtt to your project:

yarn add rc-mqtt

Hooks availables

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

Usage

Currently, rc-mqtt 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 'rc-mqtt';
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 'rc-mqtt';

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 'rc-mqtt';

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 'rc-mqtt';

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

  return (
    <div>
      <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 'rc-mqtt';

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 ©

rc-mqtt's People

Contributors

andybuibui avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.