File tree Expand file tree Collapse file tree 4 files changed +34
-1
lines changed
Expand file tree Collapse file tree 4 files changed +34
-1
lines changed Original file line number Diff line number Diff line change 1+ ---
2+ " react-mqtt-hooks " : patch
3+ ---
4+
5+ fix caching
Original file line number Diff line number Diff line change 11import { Badge } from "@/components/ui/badge" ;
22import { MqttConnector } from "react-mqtt-hooks" ;
33import ConnectionStatus from "./components/connection-status" ;
4+ import Demo from "./components/demo" ;
45import MultiTopicsCard from "./components/multi-topics-card" ;
56import SingleTopicCard from "./components/single-topic-card" ;
67import { Button } from "./components/ui/button" ;
@@ -24,7 +25,7 @@ function App() {
2425 < span className = "font-bold" > { MQTT_URL } </ span >
2526 </ Badge >
2627 </ div >
27- < p className = "" >
28+ < p >
2829 You can now publish message to topic
2930 { " " }
3031 < span className = "px-1.5 py-0.5 bg-zinc-200 rounded-lg font-mono font-medium" > chat/1</ span >
@@ -62,6 +63,7 @@ function App() {
6263 < MultiTopicsCard />
6364 </ main >
6465
66+ < Demo />
6567 </ div >
6668 </ MqttConnector >
6769 ) ;
Original file line number Diff line number Diff line change 1+ import { useState } from "react" ;
2+ import SingleTopicCard from "./single-topic-card" ;
3+ import { Button } from "./ui/button" ;
4+
5+ export default function Demo ( ) {
6+ const [ show , setShow ] = useState ( false ) ;
7+ return (
8+ < section className = "space-y-2" >
9+
10+ < p >
11+ Component mount/unmount should get the data from cache.
12+ </ p >
13+ < Button onClick = { ( ) => setShow ( ! show ) } variant = "outline" size = "lg" >
14+ { show ? "Hide" : "Show" }
15+ </ Button >
16+
17+ { show && < SingleTopicCard topic = "chat/1" /> }
18+ </ section >
19+ ) ;
20+ }
Original file line number Diff line number Diff line change @@ -21,6 +21,12 @@ export default function useTopic<T = any>(topic: string | null) {
2121 mqttClient . subscribe ( topic ) ;
2222 }
2323
24+ // when multiple components subscribe to the same topic, return the data from the cache
25+ const cachedData = cache . getData < T > ( topic ) ;
26+ if ( cachedData ) {
27+ setData ( cachedData ) ;
28+ }
29+
2430 const handleDataUpdate = ( newData : T ) => {
2531 setData ( newData ) ;
2632 } ;
You can’t perform that action at this time.
0 commit comments