Skip to content

Support for Immer #5

@raybooysen

Description

@raybooysen

Immer is a library that allows a developer to work on a draft of state instead of recreating the state for each handled action.

An example of a reducer:

import produce from "immer"

const baseState = [
    {
        todo: "Learn typescript",
        done: true
    },
    {
        todo: "Try immer",
        done: false
    }
];

const nextState = produce(baseState, draftState => {
    draftState.push({todo: "Tweet about it"})
    draftState[1].done = true
});

It would be nice to support this in safe-redux. The changes are quite simple, but the major question is how we support that inside this package. for example, an immer implementation of Handler could be changed to:

export type Handler<State, ActionType extends string, Actions> = (
  draft: Draft<State>,
  state: State,
  action: ActionsOfType<Actions, ActionType>,
) => State;

Where we introduce the draft that is mutable and part of immer. At the same time, we need to have an implementation of handleActions that looks something like this:

export function handleActions<
  State,
  Types extends string,
  Actions extends ActionsUnion<{ [T in Types]: ActionCreator }>
>(handlers: { [T in Types]: Handler<State, T, Actions> }, initialState: State) {
  return (state = initialState, action: Actions): State => {
    return produce(state, draft => {
        const handler = handlers[action.type];
        return handler ? handler(state, action) : state;
    }
  };
}```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions