-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredux.tsx
83 lines (66 loc) · 1.7 KB
/
redux.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
//
// store.ts
//
import { createStore } from 'redux';
// Define the shape of the state
interface CounterState {
value: number;
}
// Define the initial state
const initialState: CounterState = {
value: 0,
};
// Define action types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
// Define action creators
interface IncrementAction {
type: typeof INCREMENT;
}
interface DecrementAction {
type: typeof DECREMENT;
}
export type CounterActionTypes = IncrementAction | DecrementAction;
export const increment = (): IncrementAction => ({ type: INCREMENT });
export const decrement = (): DecrementAction => ({ type: DECREMENT });
// Define the reducer
function counterReducer(
state = initialState,
action: CounterActionTypes
): CounterState {
switch (action.type) {
case INCREMENT:
return { value: state.value + 1 };
case DECREMENT:
return { value: state.value - 1 };
default:
return state;
}
}
// Create the Redux store
export const store = createStore(counterReducer);
//
// App.tsx
//
import React from 'react';
import { Provider, useDispatch, useSelector } from 'react-redux';
import { store, increment, decrement } from './store';
// Define a selector for the state
const selectValue = (state: { value: number }) => state.value;
const Counter: React.FC = () => {
const dispatch = useDispatch();
const value = useSelector(selectValue);
return (
<div>
<h1>Counter: {value}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
};
const App: React.FC = () => (
<Provider store={store}>
<Counter />
</Provider>
);
export default App;