Saturday, May 19, 2018

Redux Reducer Perfection with Immer




All of these achieves the same thing. The last one is the perfect one.

export function counterReducer(
    state: ICounterMore = {count: 0, message: 'hello'},
    action: ICounterAction
) // : ICounterMore, automatically inferred from return produce
{
    return produce(state, draft => {
        switch (action.type) {
            case CounterKind.INCREMENT:
                ++draft.count;
                break;
            case CounterKind.DECREMENT:
                --draft.count;
                draft.message = 'hey';
                break;
        }
    });
}


export const counterReducer = (
    state: ICounterMore = {count: 0, message: 'hello'},
    action: ICounterAction
) // : ICounterMore, automatically inferred from return type of produce
    => produce(state, draft =>
    {
        switch (action.type) {
            case CounterKind.INCREMENT:
                ++draft.count;
                break;
            case CounterKind.DECREMENT:
                --draft.count;
                draft.message = 'hey';
                break;
        }
    });


export const counterReducer = produce((
    draft: ICounterMore = {count: 0, message: 'hello'},
    action: ICounterAction
) // : ICounterMore, automatically inferred from return draft
=> {
    switch (action.type) {
        case CounterKind.INCREMENT:
            ++draft.count;
            break;
        case CounterKind.DECREMENT:
            --draft.count;
            draft.message = 'hey';
            break;
    }
    return draft;
});

No comments:

Post a Comment