Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Immer #5

Open
raybooysen opened this issue Jun 17, 2019 · 1 comment
Open

Support for Immer #5

raybooysen opened this issue Jun 17, 2019 · 1 comment

Comments

@raybooysen
Copy link

raybooysen commented Jun 17, 2019

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;
    }
  };
}```
@gillchristian
Copy link
Contributor

gillchristian commented Sep 8, 2019

Hello @raybooysen

Interesting question. I'm aware of Immer, but haven't used it myself.

I'm not sure if adding Immer support is the best idea. This library is pretty basic, if you remove the types you have just a few lines of code. And we'd like to keep it that way.

Maybe you can fork it and publish it on your own? E.g. safe-redux-immer.

If you do that, please let me know so I can update the README and point to it for those looking to use Immer.

Wdyt?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants