Last active
September 19, 2019 15:26
-
-
Save MJGTwo/34fbd379253f61e61d1abe09f82ba8a2 to your computer and use it in GitHub Desktop.
an example of redux using 3 actions for a counter: increment, decrement, and reset.
This file contains 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
// ./counter/types.ts | |
export interface CounterState { | |
value: number; | |
} | |
export const INCREMENT_COUNTER = "INCREMENT_COUNTER"; | |
export const DECREMENT_COUNTER = "DECREMENT_COUNTER"; | |
export const RESET_COUNTER = "RESET_COUNTER"; | |
export interface IncrementCounterAction { | |
type: typeof INCREMENT_COUNTER; | |
step: number; | |
} | |
export interface DecrementCounterAction { | |
type: typeof DECREMENT_COUNTER; | |
step: number; | |
} | |
export interface ResetCounterAction { | |
type: typeof RESET_COUNTER; | |
value: number; | |
} | |
export type CounterActionTypes = | |
| IncrementCounterAction | |
| DecrementCounterAction | |
| ResetCounterAction; | |
// ./counter/actions.ts | |
import { | |
INCREMENT_COUNTER, | |
DECREASE_COUNTER, | |
RESET_COUNTER, | |
IncrementCounterAction, | |
DecrementCounterAction, | |
ResetCounterAction, | |
CounterState | |
} from "./types"; | |
export const incrementCounter = (step = 1): IncrementCounterAction => ({ | |
type: INCREMENT_COUNTER, | |
step | |
}); | |
export const decrementCounter = (step = 1): DecrementCounterAction => ({ | |
type: DECREMENT_COUNTER, | |
step | |
}); | |
export const resetCounter = (value = 0): ResetCounterAction => ({ | |
type: RESET_COUNTER, | |
value | |
}); | |
// ./counter/reducers.ts | |
import { | |
INCREMENT_COUNTER, | |
DECREASE_COUNTER, | |
RESET_COUNTER, | |
IncrementCounterAction, | |
DecrementCounterAction, | |
ResetCounterAction, | |
CounterState | |
} from "./types"; | |
const initialState: CounterState = { | |
value: 0 | |
}; | |
export const counterReducer = ( | |
state = initialState, | |
action: CounterActionTypes | |
): CounterState => { | |
switch (action.type) { | |
case INCREMENT_COUNTER: { | |
const { step } = action; | |
return { ...state, value: state.value + step }; | |
} | |
case DECREMENT_COUNTER: { | |
const { step } = action; | |
return { ...state, value: state.value - step }; | |
} | |
case RESET_COUNTER: { | |
const { value } = action; | |
return { ...state, value }; | |
} | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment