-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: Add subscription example (#2480)
* Add subscription example * update example * move out the sub source
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import React from "react" | ||
import useSWRSubscription from "swr/subscription" | ||
import EventEmitter from "events" | ||
|
||
const event = new EventEmitter() | ||
|
||
// Simulating an external data source. | ||
let stopped = false | ||
async function start () { | ||
for (let i = 0; i < 100; i++) { | ||
await new Promise(res => setTimeout(res, 1000)) | ||
if (stopped) return | ||
if (i % 3 === 0 && i !== 0) { | ||
event.emit("error", new Error("error: " + i)); | ||
} else { | ||
event.emit("data", "state: " + i); | ||
} | ||
} | ||
} | ||
|
||
export default function page() { | ||
const { data, error } = useSWRSubscription('my-sub', (key, { next }) => { | ||
event.on("data", (value) => next(undefined, value)); | ||
event.on("error", (err) => next(err)); | ||
start(); | ||
return () => { | ||
stopped = true; | ||
}; | ||
}) | ||
|
||
return ( | ||
<div> | ||
<h3>SWR Subscription</h3> | ||
<h4>Received every second, error when data is times of 3</h4> | ||
<div>{data}</div> | ||
<div>{error ? error.message : ""}</div> | ||
</div> | ||
) | ||
} |