Created
October 16, 2019 02:53
-
-
Save geta6/92458797f487329beed3cf7d38425526 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
}); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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