-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReactTasksQueueExample.tsx
60 lines (49 loc) · 1.27 KB
/
ReactTasksQueueExample.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import * as React from 'react';
import { useTask } from '@tynik/web-workers';
const ReactTasksQueueExample = () => {
const [fibonacciNumbersResults, setFibonacciNumbersResults] = React.useState<{
number: number
fibonacci: number
tookTime: number
}[]>([]);
const [
task,
{ queueLength, isRunning }
] = useTask<[number], number>(
(number) => {
return (
function fibonacci(num) {
if (num <= 1) return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}
)(number);
});
React.useEffect(() => {
if (!task) {
return;
}
const numbers = [37, 38, 39, 40, 41];
numbers.forEach(async (number) => {
const { result: fibonacci, tookTime } = await task.run(number).whenCompleted;
setFibonacciNumbersResults(loadTaskResults => (
[
...loadTaskResults,
{
number,
fibonacci,
tookTime
}
]
));
});
}, [task]);
return (
<>
<p>Tasks queue length: {queueLength}</p>
<p>Is running: {isRunning ? 'Yes' : 'No'}</p>
<p>Task results of Fibonacci numbers:</p>
<pre>{JSON.stringify(fibonacciNumbersResults, null, 2)}</pre>
</>
);
};
export default ReactTasksQueueExample;