Created
February 16, 2019 14:50
-
-
Save velopert/ed28efaa4baeeba5f61610bd39d1872a to your computer and use it in GitHub Desktop.
Redux + TypeScript
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 { | |
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; |
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
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