Search code examples
typescriptredux

Redux mapDispatchToProps throws TS error when rewritten from JS toTS (Expected 1 arguments, but got 2.)


I have rather limited experience with TS. When rewriting perfectly working js code

const mapDispatchToProps = (dispatch) => ({
    thunkFetchIndividualBook: (redirect, id) => dispatch(thunkFetchIndividualBook(redirect, id)),
});
    

where thunkFetchIndividualBooks is as follows:


interface thunkFetchIndividualBookArgsType {
    redirect: RedirectType;
    id: string;
}
const thunkFetchIndividualBook = ({
    redirect,
    id,
}: thunkFetchIndividualBookArgsType): ThunkAction<void, RootStateType, unknown, AnyAction> => {
    return async dispatch => {
        const path = googleAPI + id;
        dispatch(fetchDetails(path));
        redirect.individualBook!();
    };
};

export default thunkFetchIndividualBook;

It tells that Expected 1 arguments, but got 2. What is the problem here?

useDispatchAction is like this:

const useDispatchAction = () => {
    const dispatch = useDispatch();
    return bindActionCreators(actionCreators, dispatch);
};

Solution

  • It should be thunkFetchIndividualBook({redirect, id}), not thunkFetchIndividualBook(redirect, id).

    That said, connect is a legacy api and you should not be using connect/mapStateToProps/mapDispatchToProps nowadays unless you are working with legacy class components.

    If you are using function components, please consider using the useSelector and useDispatch hooks instead.

    Generally, if you are just learning Redux and your course is showing switch..case reducers, ACTION_TYPES or immutable reducer logic, that is not part of modern Redux any more. In that case I would highly recommend you to read through the official Redux tutorial. Modern Redux is just 1/4 of the code and a lot easier to use with TypeScript in specific.