1 Answer
- Newest
- Most votes
- Most comments
0
The Amplify PubSub module creates the MQTT WSS connection only when subscribe
is invoked, this is why you do not see any publishes if you do not subscribe first. If your application only needs to publish data but not subscribe, you can just call subscribe
with an empty array of topics to trigger the connection. Otherwise the publish topics are not correlated to the subscribe topics, ie you can subscribe to topic response
and publish to topic answer
. Just ensure that you have called subscribe
once before calling publish
.
See example snippet below.
import { useEffect, useState } from 'react'; import reactLogo from './assets/react.svg'; import viteLogo from '/vite.svg'; import { PubSub } from '@aws-amplify/pubsub'; import '@aws-amplify/ui-react/styles.css'; import './App.css'; import { withAuthenticator } from '@aws-amplify/ui-react'; import { fetchAuthSession } from 'aws-amplify/auth'; const pubsub = new PubSub({ endpoint: 'wss://abcdxxxxxxx-ats.iot.eu-west-1.amazonaws.com/mqtt', region: 'eu-west-1', }); function App() { const [count, setCount] = useState(0); useEffect(() => { console.log('Publishing ', count); pubsub .publish({ topics: 'hello', message: { msg: `Hello ${count}` }, }) .catch((err) => console.error(err)); }, [count]); useEffect(() => { fetchAuthSession().then((info) => { console.log(info.identityId); }); // This triggers the connection to the AWS IoT MQTT broker pubsub.subscribe({ topics: [] }).subscribe({}); }, []); return ( <> <div> <h1>Vite + React</h1> <div className="card"> <button onClick={async () => { setCount((count) => count + 1); }} > count is {count} </button> <p> Edit <code>src/App.tsx</code> and save to test HMR </p> </div> </> ); } export default withAuthenticator(App);
Relevant content
- asked 7 months ago
- asked 3 years ago
- Accepted Answerasked 2 years ago
- asked a year ago
- AWS OFFICIALUpdated 3 months ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 3 years ago
- AWS OFFICIALUpdated 2 years ago