Typescript
で react/redux
の ducksパターンをやるとき。
modules
modules/counter.module.ts
export type CounterState = {
count: number;
};
type IncrementCountAction = {
type: 'INCREMENT_COUNT',
}
type DecrementCountAction = {
type: 'DECREMENT_COUNT',
}
type SetCountAction = {
type: 'SET_COUNT',
count: number,
}
export type CounterActions = IncrementCountAction | DecrementCountAction | SetCountAction;
export default (
state: CounterState = { count: 0 }, action: CounterActions
): CounterState => {
switch (action.type) {
case 'INCREMENT_COUNT':
return { ...state, count: state.count + 1 };
case 'DECREMENT_COUNT':
return { ...state, count: state.count - 1 };
case 'SET_COUNT':
return { ...state, count: action.count };
default: return state;
}
};
store
store.ts
import { combineReducers, createStore, Dispatch } from 'redux';
import counter, { CounterState, CounterActions } from './modules/counter.moudle';
import user, { UserState, UserActions } from './modules/user.moudle';
export type RootState = {
counter: CounterState,
user: UserState,
};
export type RootDispatch = Dispatch<CounterActions | UserActions>;
export const rootReducer = combineReducers({ counter, user });
how to use
component.tsx
const dispatch = useDispatch<RootDispatch>();
const count = useSelector<RootState, number>(s => s.counter.count);
dispatch({ type: 'INCREMENT_COUNT' });