I have a react APP that uses the AWS Amplify PubSub library.
I have an IoT device that connect to AWS IoT and publishes message on topic/pub
(topic).The message is only sent once (from the device) and when I see it in the AWS MQTT client console I can only see only 1 message (as expected) but in the react application I'm receiving multiple messages in the console.
App.js
...
import {Amplify} from 'aws-amplify';
import awsconfig from './aws-exports';
// import { withAuthenticator } from 'aws-amplify-react'; // or 'aws-amplify-react-native';
import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
import { Auth } from 'aws-amplify';
Amplify.configure(awsconfig);
// Auth.currentCredentials().then(creds => console.log(creds));
function App() {
return (
...
export default withAuthenticator(App,true);
Device Page.js
import {Amplify} from 'aws-amplify';
import awsconfig from './../aws-exports';
import { PubSub } from 'aws-amplify';
import { AWSIoTProvider } from '@aws-amplify/pubsub/lib/Providers';
Amplify.configure(awsconfig);
Amplify.addPluggable(new AWSIoTProvider({
aws_pubsub_region: 'xx-xxxxxxx-x',
aws_pubsub_endpoint: 'wss://<My endpoint from AWS IoT>/mqtt',
}));
function GaugesComponent ({id}) {
PubSub.subscribe('test/pub').subscribe({
next: data => {
console.log(data.value);
},
error: error => console.error(error),
complete: () => console.log('Done'),
},);
return (
...
export default GaugesComponent;
When my device publishes or I use the AWS MQTT client to publish a message the message is logged multiple times in the console.
Images:
AWS MQTT client console
console log messages of react app
Instead of adding the below code in the device.js where I'm subscribing to the MQTT topic I only added it once in my app.js
after Amplify.configure();
like this
App.js
Amplify.configure(awsconfig);
Amplify.addPluggable(new AWSIoTProvider({
aws_pubsub_region: 'xx-xxxxxxx-x',
aws_pubsub_endpoint: 'wss://<My endpoint from AWS IoT>/mqtt',
}));
Then I subscribe to the topic using useEffect()
like this in my device.js
Device.js
sub_topic = PubSub.subscribe(id+'/live').subscribe({
next: data => {/*do stuff with received data*/},
error: error => console.error(error),
complete: () => console.log('Done'),
},);
return ()=>{
sub_topic.unsubscribe();
console.log("Unsubscribed to topic");
}
},[]);