-
-
Notifications
You must be signed in to change notification settings - Fork 15.2k
Description
I've been playing around with react redux and flow in some projects. I like it, but there is one thing I hate: adding an action creator. The problem is, that I have to change stuff, in 3 files, and it is very repetitive. I will show an example:
src/ActionModal/actions.js
import ActionTypes from "./ActionTypes";
export type ShowActionModal = {
type: 'ShowActionModal'
}
function show(): ShowActionModal {
return {
type: ActionTypes.show
}
}
export type HideActionModal = {
type: 'HideActionModal'
}
function hide(): HideActionModal {
return {
type: ActionTypes.hide
}
}
export default {show, hide};
src/ActionModal/ActionTypes.js
const show = 'ActionModal/show';
const hide = 'ActionModal/hide';
export default {show, hide};
src/Action.js
import {Increment, Decrement} from './Counter/actions';
import {ShowActionModal, HideActionModal} from './ActionModal/actions';
export type Action = Increment | Decrement | ShowActionModal | HideActionModal;
I have to type 4 times the word ShowActionModal
, just to add one simple action creator to my project. This just seems like so much work, for just two simple actions.
I'm wondering if you guys have thought about supporting the following pattern:
src/ActionModal/actions.js
class ShowActionModal extends Action {}
class HideActionModal extends Action {}
src/Action.js
class Action {
constructor() {
// here you can for example log that an action is created ...
// or nothing :-)
}
}
This is much less code. There is no need for hardcoding an action constant. And now you can just change one file, anytime you create an action creator (the constructor is now the action creator). There is no need to declare a type, because a class is a type.
The reducer would look like this:
function showModalReducer(state, action) {
switch (action.constructor) {
case ShowActionModal:
return true;
case HideActionModal:
return false;
default:
return state;
}
}
Also if you would have some more complex actions, you can do this like this of course:
class ToggleTodo extends Action {
id: number;
constructor(id: number){ this.id = id; }
}
Tagging @gcanti as I saw that he has some experience with using redux with flow.