Skip to content

Commit

Permalink
chore: refactor with-web-worker example (#40844)
Browse files Browse the repository at this point in the history
## Changes

- Updated dependencies
- Migrated to typescript
- Removed `div` in favour of Fragment
- Replaces `var` with `let` since we don't need global hoisting here

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [x] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
  • Loading branch information
HaNdTriX committed Sep 23, 2022
1 parent 6a11e22 commit cc7fd2c
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 11 deletions.
9 changes: 7 additions & 2 deletions examples/with-web-worker/package.json
Expand Up @@ -7,7 +7,12 @@
},
"dependencies": {
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2"
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "18.7.18",
"@types/react": "16.9.17",
"typescript": "4.8.2"
}
}
@@ -1,11 +1,12 @@
import { useEffect, useRef, useCallback } from 'react'

export default function Index() {
const workerRef = useRef()
const workerRef = useRef<Worker>()

useEffect(() => {
workerRef.current = new Worker(new URL('../worker.js', import.meta.url))
workerRef.current.onmessage = (evt) =>
alert(`WebWorker Response => ${evt.data}`)
workerRef.current = new Worker(new URL('../worker.ts', import.meta.url))
workerRef.current.onmessage = (event: MessageEvent<number>) =>
alert(`WebWorker Response => ${event.data}`)
return () => {
workerRef.current.terminate()
}
Expand All @@ -16,9 +17,9 @@ export default function Index() {
}, [])

return (
<div>
<>
<p>Do work in a WebWorker!</p>
<button onClick={handleWork}>Calculate PI</button>
</div>
</>
)
}
20 changes: 20 additions & 0 deletions examples/with-web-worker/tsconfig.json
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
@@ -1,6 +1,6 @@
// https://stackoverflow.com/a/39575124
export default function pi(n) {
var v = 0
export default function pi(n: number) {
let v = 0
for (let i = 1; i <= n; i += 4) {
// increment by 4
v += 1 / i - 1 / (i + 2) // add the value of the series
Expand Down
@@ -1,6 +1,6 @@
// This is a module worker, so we can use imports (in the browser too!)
import pi from './utils/pi'

addEventListener('message', (event) => {
addEventListener('message', (event: MessageEvent<number>) => {
postMessage(pi(event.data))
})

0 comments on commit cc7fd2c

Please sign in to comment.