LoginSignup
1
0

More than 3 years have passed since last update.

React + Redux + TypeScript で Ducks パターン

Last updated at Posted at 2020-03-17

Typescriptreact/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' });
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0