I have an asynchronous redux action and so am using the thunk middleware.
I have mapStateToProps
, mapDispatchToProps
and connect
functions for a component as follows:
const mapStateToProps = (store: IApplicationState) => {
return {
loading: store.products.loading,
products: store.products.products
};
};
const mapDispatchToProps = (dispatch: any) => {
return {
getAllProducts: () => dispatch(getAllProducts())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ProductsPage);
This all works but I wondered if is possible to replace the any
type on the dispatch parameter in mapDispatchToProps
?
I tried ThunkDispatch<IApplicationState, void, Action>
but get the following TypeScript error on the connect function:
Argument of type 'typeof ProductsPage' is not assignable to parameter of type 'ComponentType<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>>'.
Type 'typeof ProductsPage' is not assignable to type 'ComponentClass<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>, any>'.
Types of property 'getDerivedStateFromProps' are incompatible.
Type '(props: IProps, state: IState) => { products: IProduct[]; search: string; }' is not assignable to type 'GetDerivedStateFromProps<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>, any>'.
Types of parameters 'props' and 'nextProps' are incompatible.
Type 'Readonly<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>>' is not assignable to type 'IProps'.
Types of property 'getAllProducts' are incompatible.
Type '() => Promise<void>' is not assignable to type '() => (dispatch: Dispatch<AnyAction>) => Promise<void>'.
Type 'Promise<void>' is not assignable to type '(dispatch: Dispatch<AnyAction>) => Promise<void>'.
Type 'Promise<void>' provides no match for the signature '(dispatch: Dispatch<AnyAction>): Promise<void>'.
Is it possible to replace the any
type on the dispatch parameter in mapDispatchToProps
?
In order to correctly dispatch thunks, you need to use the specific customized AppDispatch type from the store that includes the thunk middleware types, and use that with useDispatch . Adding a pre-typed useDispatch hook keeps you from forgetting to import AppDispatch where it's needed.
Where does this new dispatch argument come from? The short answer is that the redux-thunk middleware has access to the store, and can therefore pass in the store's dispatch and getState when invoking the thunk. The middleware itself is responsible for injecting those dependencies into the thunk.
As of React-Redux v8, React-Redux is fully written in TypeScript, and the types are included in the published package. The types also export some helpers to make it easier to write typesafe interfaces between your Redux store and your React components.
This setup works very well for me:
// store.ts
//...
export type TAppState = ReturnType<typeof rootReducer>;
export type TDispatch = ThunkDispatch<TAppState, void, AnyAction>;
export type TStore = Store<TAppState, AnyAction> & { dispatch: TDispatch };
export type TGetState = () => TAppState;
//...
const store: TStore = createStore(
rootReducer,
composeEnhancers(applyMiddleware(...middleware), ...enhancers)
);
export default store;
Where rootReducer
on my setup looks like this const rootReducer = createRootReducer(history);
// createRootReducer.ts
import { combineReducers, Reducer, AnyAction } from 'redux';
import { History } from 'history';
import {
connectRouter,
RouterState,
LocationChangeAction,
} from 'connected-react-router';
// ... here imports of reducers
type TAction = AnyAction & LocationChangeAction<any>;
export type TRootReducer = Reducer<
{
// ... here types of the reducer data slices
router: RouterState;
},
TAction
>;
const createRootReducer = (history: History): TRootReducer =>
combineReducers({
// ... here actual inserting imported reducers
router: connectRouter(history),
});
export default createRootReducer;
Then in connected component
import { connect } from 'react-redux';
import Add, { IProps } from './Add'; // Component
import { TDispatch, TAppState } from '../../store';
type TStateProps = Pick<
IProps,
'title' | 'data' | 'loading'
>;
const mapStateToProps = (
state: TAppState,
): TStateProps => {
// ... here you have typed state :)
// and return the TStateProps object as required
return {
loading: state.someReducer.loading,
//...
}
}
type TDispatchProps = Pick<IProps, 'onSave'>;
const mapDispatchToProps = (
dispatch: TDispatch,
): TDispatchProps => {
// here you have typed dispatch now
// return the TDispatchProps object as required
return {
onSave: (): void => {
dispatch(saveEntry()).then(() => {
backButton();
});
},
}
}
As for the thunk actions I do as follows
// this is a return type of the thunk
type TPromise = Promise<ISaveTaskResponse | Error>;
export const saveEntry = (): ThunkAction<
TPromise, // thunk return type
TAppState, // state type
any, // extra argument, (not used)
ISaveEntryAction // action type
> => (dispatch: TDispatch, getState: TGetState): TPromise => {
// use getState
// dispatch start saveEntry action
// make async call
return Axios.post('/some/endpoint', {}, {})
.then((results: { data: ISaveTaskResponse; }): Promise<ISaveTaskResponse> => {
// get results
// you can dispatch finish saveEntry action
return Promise.resolve(data);
})
.catch((error: Error): Promise<Error> => {
// you can dispatch an error saveEntry action
return Promise.reject(error);
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With