-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathcreateReducerContext.story.tsx
66 lines (58 loc) · 1.52 KB
/
createReducerContext.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
import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { createReducerContext } from '../src';
import ShowDocs from './util/ShowDocs';
type Action = 'increment' | 'decrement';
const reducer = (state: number, action: Action) => {
switch (action) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
throw new Error();
}
};
const [useSharedCounter, SharedCounterProvider] = createReducerContext(reducer, 0);
const ComponentA = () => {
const [count, dispatch] = useSharedCounter();
return (
<p>
Component A
<button type="button" onClick={() => dispatch('decrement')}>
-
</button>
{count}
<button type="button" onClick={() => dispatch('increment')}>
+
</button>
</p>
);
};
const ComponentB = () => {
const [count, dispatch] = useSharedCounter();
return (
<p>
Component B
<button type="button" onClick={() => dispatch('decrement')}>
-
</button>
{count}
<button type="button" onClick={() => dispatch('increment')}>
+
</button>
</p>
);
};
const Demo = () => {
return (
<SharedCounterProvider>
<p>Those two counters share the same value.</p>
<ComponentA />
<ComponentB />
</SharedCounterProvider>
);
};
storiesOf('State/createReducerContext', module)
.add('Docs', () => <ShowDocs md={require('../docs/createReducerContext.md')} />)
.add('Demo', () => <Demo />);