Skip to content

Instantly share code, notes, and snippets.

@geta6
Created October 16, 2019 02:53
Show Gist options
  • Save geta6/92458797f487329beed3cf7d38425526 to your computer and use it in GitHub Desktop.
Save geta6/92458797f487329beed3cf7d38425526 to your computer and use it in GitHub Desktop.
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from './store';
export enum ActionTypes {
INCREMENT = 'Counter/INCREMENT',
DECREMENT = 'Counter/DECREMENT',
SET_COUNT = 'Counter/SET_COUNT',
}
export const useCounter = () => {
const dispatch = useDispatch();
const increment = () => dispatch({ type: ActionTypes.INCREMENT });
const decrement = () => dispatch({ type: ActionTypes.DECREMENT });
const setCount = (count: number) => dispatch({ type: ActionTypes.SET_COUNT, paylod: { count } });
const count = useSelector<RootState, number>((state) => state.counter.count);
return { increment, decrement, setCount, count };
};
import { produce } from 'immer';
import { Reducer, Action } from 'redux';
import { ActionTypes } from './hooks';
export interface CounterState {
count: number;
}
export const initialState: CounterState = {
count: 0,
};
export const counter: Reducer<CounterState, Action<ActionTypes>> = (currentState = initialState, action) => {
return produce(currentState, (state) => {
switch (action.type) {
case ActionTypes.INCREMENT: {
state.count += 1;
break;
}
case ActionTypes.DECREMENT: {
state.count -= 1;
break;
}
case ActionTypes.SET_COUNT: {
action.count;
}
}
});
};
import { createStore as originalCreateStore, combineReducers } from 'redux';
import { counter, CounterState } from './reducer';
export interface RootState {
counter: CounterState;
}
export const createStore = () => {
const reducer = combineReducers<RootState>({
counter,
});
return originalCreateStore(reducer, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment