Skip to content

Instantly share code, notes, and snippets.

@velopert
Created February 16, 2019 14:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velopert/ed28efaa4baeeba5f61610bd39d1872a to your computer and use it in GitHub Desktop.
Save velopert/ed28efaa4baeeba5f61610bd39d1872a to your computer and use it in GitHub Desktop.
Redux + TypeScript
import {
createAction,
createStandardAction,
ActionType,
} from 'typesafe-actions';
import { createReducer } from '../utils';
const SET_KEYWORD = 'header/SET_KEYWORD';
export const setKeyword = createStandardAction(SET_KEYWORD)<string>();
type SetKeyword = ReturnType<typeof setKeyword>;
export interface HeaderState {
keyword: string;
}
const initialState: HeaderState = {
keyword: '',
};
const reducer = createReducer<HeaderState>(
{
[SET_KEYWORD]: (state, { payload }: SetKeyword) => {
return {
...state,
keyword: payload,
};
},
},
initialState,
);
export default reducer;
export type Handlers<T> = {
[type: string]: (state: T, action: any) => T;
};
export function createReducer<S>(handlers: Handlers<S>, initialState: S) {
return (state: S = initialState, action: AnyAction) => {
const handler = handlers[action.type];
if (handler) return handler(state, action);
return state;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment