-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseStateWithHistory.story.tsx
91 lines (79 loc) Β· 2.54 KB
/
useStateWithHistory.story.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { useCallback, useRef } from 'react';
import { useCounter, useStateWithHistory } from '../src';
import ShowDocs from './util/ShowDocs';
const Demo = () => {
const [state, setState, history] = useStateWithHistory('', 10, ['hello', 'world']);
const inputRef = useRef<HTMLInputElement | null>(null);
const [stepSize, { set: setStepSize }] = useCounter(1, 3, 1);
const handleFormSubmit = useCallback(
(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
state !== inputRef.current!.value && setState(inputRef.current!.value);
},
[state]
);
const handleBackClick = useCallback(
(e: React.MouseEvent<HTMLButtonElement>) => {
if (e.currentTarget.disabled) {
return;
}
window.history.back(stepSize);
},
[history, stepSize]
);
const handleForwardClick = useCallback(
(e: React.MouseEvent<HTMLButtonElement>) => {
if (e.currentTarget.disabled) {
return;
}
window.history.forward(stepSize);
},
[history, stepSize]
);
const handleStepSizeChange = useCallback(
(e: React.FormEvent<HTMLInputElement>) => {
setStepSize((e.currentTarget.value as any) * 1);
},
[stepSize]
);
return (
<div>
<div>
<form onSubmit={handleFormSubmit} style={{ display: 'inline-block' }}>
<input type="text" ref={inputRef} />
<button>Submit new state</button>
</form>
</div>
<div style={{ marginTop: 8 }}>
Current state: <span>{state}</span>
</div>
<div style={{ marginTop: 8 }}>
<button onClick={handleBackClick} disabled={!window.history.position}>
< Back
</button>
<button
onClick={handleForwardClick}
disabled={window.history.position >= window.history.window.history.length - 1}>
Forward >
</button>
Step size:
<input type="number" value={stepSize} min={1} max={3} onChange={handleStepSizeChange} />
</div>
<div style={{ marginTop: 8 }}>
<div>Current history</div>
<div
dangerouslySetInnerHTML={{
__html: JSON.stringify(window.history.history, null, 2)
.replace(/\n/g, '<br/>')
.replace(/ /g, ' '),
}}
/>
</div>
</div>
);
};
storiesOf('State/useStateWithHistory', module)
.add('Docs', () => <ShowDocs md={require('../docs/useStateWithHistory.md')} />)
.add('Demo', () => <Demo />);