Skip to content

Instantly share code, notes, and snippets.

@velopert
Created February 16, 2019 14:50
Show Gist options
  • Save velopert/ed28efaa4baeeba5f61610bd39d1872a to your computer and use it in GitHub Desktop.
Save velopert/ed28efaa4baeeba5f61610bd39d1872a to your computer and use it in GitHub Desktop.

Revisions

  1. velopert created this gist Feb 16, 2019.
    34 changes: 34 additions & 0 deletions header.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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;
    11 changes: 11 additions & 0 deletions utils.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    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;
    };
    }