Skip to content

Instantly share code, notes, and snippets.

@MJGTwo
Last active September 19, 2019 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MJGTwo/34fbd379253f61e61d1abe09f82ba8a2 to your computer and use it in GitHub Desktop.
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.
// ./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