Dziamid
Dziamid

Reputation: 11571

Typesafe action creators in redux

I've failed countless times forgetting to extract connected action creator from props like this:

import {actionCreator} from 'my-actions';
interface Props {
  actionCreator: typeof (actionCreator);
}

const Foo: React.SFC<Props> = (props) => {
  // oh, i forgot to take actionCreator from props
  // const { actionCreator } = props; 

  return (<Button 
    onClick={actionCreator} // Santa, I wish it would fail to compile this, can you make it throw an error?
  />); 
} 

export const mapDispatch = (dispatch: Dispatch<Action>) => {
  return bindActionCreators({
     actionCreator,
  }, dispatch);
}

export const ConnectedFoo = connect(null, mapDispatch)

The above will silently compile, but you will not see any action in redux.

Upvotes: 0

Views: 434

Answers (1)

Michael Tamm
Michael Tamm

Reputation: 933

The problem is, that you imported actionCreator, so it is visible in the whole module, therefore you get no compile error.

Possible solutions:

1.) Put the container component and the presentational component into two separate files: the import, mapDispatch and ConnectedFoo would be in connected_foo.ts and Props as well as Foo would be in foo.tsx and then you get a compile error.

2.) Foo should not have a property with the name actionCreator, a better name would be action or maybe onClick -- you do not give action creators to presentational components, but actual actions.

Upvotes: 1

Related Questions