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

How to use with createReducer? #121

Closed
Dhuliang opened this issue Jan 22, 2019 · 2 comments
Closed

How to use with createReducer? #121

Dhuliang opened this issue Jan 22, 2019 · 2 comments

Comments

@Dhuliang
Copy link

Sometimes don't want to use switch case grammar , use official provide function createReducer, the link is https://redux.js.org/recipes/reducing-boilerplate#generating-reducers

I added typescript like this:

export interface PartialReducer<T, A> {
  (state: T, action: A): T;
}

export function createReducer<T, A extends { type: string }>(
  initialState: T,
  handlers: { [type: string]: PartialReducer<T, A> }
) {
  return function(state: T = initialState, action: A): T {
    const handler = handlers[action && action.type];
    if (!handler) {
      return state;
    }
    return handler(state, action);
  };
}

and Todos reducers is

createReducer<Todo[], TodosAction>([], {
  [getType(todos.add)](state = [], action): Todo[] {
    return [...state, action.payload]; //get error , don't know which payload should be 
  },
});

If I add the following script , it will remove error but it's hard to use.

export type TodosAddAction = ActionType<typeof todos.add>;
[getType(todos.add)](state = [], action: TodosAddAction): Todo[] {
    return [...state, action.payload]; 
  },
}

Can help improve above function? Thanks !

@piotrwitek
Copy link
Owner

I solved this, I'll add it soon as a new section in the guide as I think it is usefull.

@piotrwitek
Copy link
Owner

For reference this issue is continued here: piotrwitek/typesafe-actions#106

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

No branches or pull requests

2 participants