Skip to content
This repository has been archived by the owner on Mar 24, 2023. It is now read-only.

Commit

Permalink
Merge branch 'release/2.0.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
VictorHAS committed Jan 10, 2021
2 parents 2e74f5e + 0405477 commit 70122dd
Show file tree
Hide file tree
Showing 31 changed files with 5,348 additions and 9,155 deletions.
17 changes: 8 additions & 9 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const { resolve } = require('path');

module.exports = {
env: {
browser: true,
Expand All @@ -17,7 +15,6 @@ module.exports = {
tsx: true,
},
sourceType: 'module',
project: resolve(__dirname, 'tsconfig.json'),
},
parser: '@typescript-eslint/parser',
plugins: [
Expand Down Expand Up @@ -47,15 +44,17 @@ module.exports = {
extensions: ['.jsx', '.tsx'],
},
],
'react/jsx-filename-extension': [
'warn',
{
extensions: ['.jsx', '.tsx'],
},
],
'import-helpers/order-imports': [
'warn',
{
'newlines-between': 'always',
groups: [
'/^react/',
['builtin', 'external', 'internal'],
['parent', 'sibling', 'index'],
],
newlinesBetween: 'always',
groups: ['/^react/', 'module', '/^~/', ['parent', 'sibling', 'index']],
alphabetize: { order: 'asc', ignoreCase: true },
},
],
Expand Down
74 changes: 70 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,8 +1,74 @@
node_modules
yarn-error.log
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage/

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

dist
# Typescript v1 declaration files
typings

__tests__/coverage
# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# dotenv environment variable files
.env*

# Library
dist/
typings/

# gatsby files
.cache/
public/

# Mac files
.DS_Store

# Yarn
yarn-error.log
.pnp/
.pnp.js

# Yarn Integrity file
.yarn-integrity
2 changes: 1 addition & 1 deletion .lintstagedrc.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"src/**/*.{js,ts,tsx}": ["eslint --ext js,ts,tsx --fix", "git add"]
"lib/*.{js,ts,tsx}": ["eslint --ext js,ts,tsx --fix"]
}
3 changes: 2 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"singleQuote": true,
"trailingComma": "es5"
"trailingComma": "all",
"arrowParens": "avoid"
}
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: node_js

node_js:
- '10'
- '12.18.0'

cache:
yarn: true
Expand Down
74 changes: 55 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ yarn add mqtt-react-hooks

### Hooks availables

- useMqttState -> return { status, mqtt, allMessages, lastMessage }
- useSubscription(topic) -> return { msgs, mqtt, status, lastMessage, lastMessageOnTopic }
- useMqttState -> return { connectionStatus, client, message }
- useSubscription(topic: string | string[], options?: {} ) -> return { client, topic, message, connectionStatus }

### Usage
Currently, mqtt-react-hooks exports one enhancers.
Expand All @@ -49,7 +49,7 @@ import Status from './Status';

export default function App() {
return (
<Connector brokerUrl="mqtt://test.mosquitto.org:8080">
<Connector brokerUrl="mqtt://test.mosquitto.org:1884">
<Status />
</Connector>
);
Expand All @@ -66,15 +66,16 @@ export default function Status() {

/*
* Status list
* - offline
* - connected
* - reconnecting
* - closed
* - Offline
* - Connected
* - Reconnecting
* - Closed
* - Error: printed in console too
*/
const { status } = useMqttState();
const { connectionStatus } = useMqttState();

return (
<h1>{`Status: ${status}`}</h1>
<h1>{`Status: ${connectionStatus}`}</h1>
);
}
```
Expand All @@ -90,10 +91,10 @@ import React from 'react';
import { useMqttState } from 'mqtt-react-hooks';

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

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

return (
Expand All @@ -113,26 +114,61 @@ import { useSubscription } from 'mqtt-react-hooks';
export default function Status() {

/* Message structure:
* id: auto-generated uuidv4
* topic: string
* message: object || string
* message: string
*/
const { msgs } = useSubscription('room/esp32/teste');
const { message } = useSubscription(['room/esp32/testing','room/esp32/light']);

return (
<>
<div style={{ display: 'flex', flexDirection: 'column' }}>
{msgs?.map(message => (
<span key={message.id}>
{`topic:${message.topic} - message: ${message.message}`}
</span>
))}
<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:
```js
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="mqtt://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.
Expand Down
73 changes: 73 additions & 0 deletions __tests__/Connector.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React from 'react';

import { renderHook, act } from '@testing-library/react-hooks';

import { useMqttState, Connector } from '../lib';
import { URL, options } from './connection';

let wrapper;

describe('Connector wrapper', () => {
beforeAll(() => {
wrapper = ({ children }) => (
<Connector brokerUrl={URL} options={options}>
{children}
</Connector>
);
});

it('should not connect with mqtt, wrong url', async () => {
const { result, waitForValueToChange } = renderHook(() => useMqttState(), {
wrapper: ({ children }) => (
<Connector
brokerUrl="mqtt://test.mosqu.org:1884"
options={{ connectTimeout: 2000 }}
>
{children}
</Connector>
),
});

await waitForValueToChange(() => result.current.connectionStatus);

expect(result.current.connectionStatus).toBe(
'getaddrinfo ENOTFOUND test.mosqu.org',
);

await waitForValueToChange(() => result.current.connectionStatus);

expect(result.current.connectionStatus).toBe('Offline');
});

it('should connect with mqtt', async () => {
const { result, wait } = renderHook(() => useMqttState(), {
wrapper,
});

await wait(() => result.current.client?.connected === true);

expect(result.current.connectionStatus).toBe('Connected');

await act(async () => {
await result.current.client?.end();
});
});

it('should connect passing props', async () => {
const { result, wait } = renderHook(() => useMqttState(), {
wrapper: ({ children }) => (
<Connector brokerUrl={URL} options={{ keepalive: 0 }}>
{children}
</Connector>
),
});

await wait(() => result.current.client?.connected === true);

expect(result.current.connectionStatus).toBe('Connected');

await act(async () => {
await result.current.client?.end();
});
});
});
2 changes: 2 additions & 0 deletions __tests__/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const URL = 'mqtt://127.0.0.1:1883';
export const options = {};
Loading

0 comments on commit 70122dd

Please sign in to comment.