|
1 |
| -import React from "react"; |
2 |
| -import {useState} from "react"; |
| 1 | +import React, {useState} from "react"; |
3 | 2 | import {
|
4 |
| - useAsyncCallback, |
5 |
| - useAsyncWatcher, |
| 3 | + useAsyncCallback |
6 | 4 | } from "../../lib/use-async-effect";
|
7 |
| -import cpAxios from "cp-axios"; |
8 |
| -import {CPromise} from "c-promise2" |
| 5 | +import {CPromise} from "c-promise2"; |
9 | 6 |
|
10 | 7 | export default function TestComponent7(props) {
|
11 |
| - const [text, setText] = useState(""); |
12 |
| - const [value, setValue] = useState(0); |
13 |
| - const [input, setInput] = useState(""); |
14 |
| - |
15 |
| - const [fn, cancel, pending, done, result, err, canceled, paused] = useAsyncCallback(function* () { |
16 |
| - for(const stage of ['stage1', 'stage2', 'stage3', 'stage4', 'stage5']){ |
17 |
| - setText(`Stage: ${stage}`); |
18 |
| - yield CPromise.delay(1000); |
19 |
| - } |
20 |
| - return "Done"; |
21 |
| - }, {states: true, deps: [value]}) |
| 8 | + const [text, setText] = useState("one two three four five"); |
| 9 | + const [word, setWord] = useState(""); |
22 | 10 |
|
| 11 | + const go = useAsyncCallback( |
| 12 | + function* (text, delay) { |
| 13 | + const words = text.split(/\s+/); |
| 14 | + for (const word of words) { |
| 15 | + setWord(word); |
| 16 | + yield CPromise.delay(delay); |
| 17 | + } |
| 18 | + }, |
| 19 | + { states: true, cancelPrevios: true } |
| 20 | + ); |
23 | 21 |
|
24 | 22 | return (
|
25 | 23 | <div className="component">
|
26 |
| - <div className="caption">useAsyncCallback pause demo:</div> |
27 |
| - <div>{text}</div> |
28 |
| - <div>{pending ? "loading..." : (done ? err ? err.toString() : JSON.stringify(result, null, 2) : "")}</div> |
29 |
| - <button onClick={fn} disabled={pending}>Run</button> |
30 |
| - <button onClick={paused? fn.resume : fn.pause} disabled={!pending}>{paused? "Resume" : "Pause"}</button> |
31 |
| - <button onClick={cancel} disabled={!pending}>Cancel async effect</button> |
| 24 | + <div className="caption">useAsyncEffect demo</div> |
| 25 | + <input |
| 26 | + value={text} |
| 27 | + onChange={({ target }) => { |
| 28 | + setText(target.value); |
| 29 | + }} |
| 30 | + /> |
| 31 | + <div>{go.error ? go.error.toString() : word}</div> |
| 32 | + {go.pending ? ( |
| 33 | + go.paused ? ( |
| 34 | + <button className="btn btn-warning" onClick={go.resume}> |
| 35 | + Resume |
| 36 | + </button> |
| 37 | + ) : ( |
| 38 | + <button className="btn btn-warning" onClick={go.pause}> |
| 39 | + Pause |
| 40 | + </button> |
| 41 | + ) |
| 42 | + ) : ( |
| 43 | + <button className="btn btn-warning" onClick={() => go(text, 1000)}> |
| 44 | + Run |
| 45 | + </button> |
| 46 | + )} |
| 47 | + {go.pending && ( |
| 48 | + <button className="btn btn-warning" onClick={go.cancel}> |
| 49 | + Cancel request |
| 50 | + </button> |
| 51 | + )} |
32 | 52 | </div>
|
33 | 53 | );
|
34 | 54 | }
|
0 commit comments