Skip to content

Instantly share code, notes, and snippets.

@kuzvac
Last active February 22, 2019 08:59
Show Gist options
  • Save kuzvac/7b6bb5c146fcf42f47de5bea6eaf5a9d to your computer and use it in GitHub Desktop.
Save kuzvac/7b6bb5c146fcf42f47de5bea6eaf5a9d to your computer and use it in GitHub Desktop.
mapDispatchToProps typesafe-actions
import { buildAction } from 'typesafe-actions';
export const authActions = {
logOut: buildAction('AUTH_LOGOUT').empty()
}
import * as React from "react";
interface IOwnProps {
someDispatchProps: () => void,
someMapStateToProps: "string",
someProps: "string",
}
export const ChildComponent: React.StatelessComponent<IOwnProps> = ({someDispatchProps, someMapStateToProps, someProps}) => {
return (
<div>
<button type="button" onClick={someDispatchProps}>{someProps}</button>
</div>
)
import * as React from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {IRootState} from 'src/redux/root-reducer';
import {Dispatch} from 'src/redux/types';
import {authActions} from 'src/containers/auth/actions';
interface IOwnProps {
someProps: "string",
}
interface IStateProps {
someMapStateToProps: "string",
}
interface IDispatchProps {
someDispatchProps: () => void,
}
type ComponentProps = IOwnProps & IStateProps & IDispatchProps;
class ParentComponent extends React.Component<ComponentProps, {}> {
public render() {
return (
<ChildComponent
someprops={this.props.someProps}
someMapStateToProps={this.props.someMapStateToProps}
someDispatchProps={this.props.someDispatchProps}
/>
)
}
}
const mapStateToProps = (state: IRootState) => ({
someMapStateToProps: state.auth.username,
});
const mapDispatchToProps = (dispatch: Dispatch) => bindActionCreators({
someDispatchProps: authActions.logOut,
}, dispatch);
export const ParentContainerContainer = connect<IStateProps>(mapStateToProps, mapDispatchToProps)(ParentComponent);
import { ActionsUnion } from 'typesafe-actions';
import { authActions } from 'src/containers/auth/actions'
const actions = {
...authActions
};
export type RootAction = ActionsUnion<typeof actions>;
Like in https://github.com/piotrwitek/react-redux-typescript-guide/blob/master/playground/src/redux/root-reducer.ts
import {
Dispatch as ReduxDispatch,
} from 'redux';
import { RootAction } from "src/redux/root-action";
export type Dispatch = ReduxDispatch<RootAction>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment