Skip to content

Commit 667596a

Browse files
committed
fix caching
1 parent 7430af6 commit 667596a

File tree

4 files changed

+34
-1
lines changed

4 files changed

+34
-1
lines changed

.changeset/nice-trees-joke.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-mqtt-hooks": patch
3+
---
4+
5+
fix caching

example/src/App.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Badge } from "@/components/ui/badge";
22
import { MqttConnector } from "react-mqtt-hooks";
33
import ConnectionStatus from "./components/connection-status";
4+
import Demo from "./components/demo";
45
import MultiTopicsCard from "./components/multi-topics-card";
56
import SingleTopicCard from "./components/single-topic-card";
67
import { 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
);

example/src/components/demo.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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+
}

src/hooks/use-topic.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff 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
};

0 commit comments

Comments
 (0)