skip to Main Content

Below is the CreateCoursePage component where I use react-redux to manage the state after some database operations. However dispatch(CreateCourse(course) statement inside mapDispatchToProps throws this exception: TS2345 (TS) Argument of type '(dispatch: Dispatch) => void' is not assignable to parameter of type 'AnyAction'.

interface CreateCourseProps {
    error: string;
    createCourse: (course: Course) => ReturnType<typeof CreateCourse>;
}

const CreateCoursePage: React.FC<CreateCourseProps> = ({ createCourse }) => {
    
    const onSubmit = (course: Course) => {
        createCourse(course);
    };

    return (
        //other code
    );
};

const mapStateToProps = (state: any) => ({
    error: state.courseReducer.error
})

const mapDispatchToProps = (dispatch: Dispatch) => ({
    createCourse: (course: Course) => dispatch(CreateCourse(course)), 
});

const ConnectedCreateCourse = connect(mapStateToProps, mapDispatchToProps)(CreateCoursePage);
export default ConnectedCreateCourse;

Below is the CreateCourse function defined in DataOperations.tsx:

export function CreateCourse(course: CourseData) {
    return async (dispatch: Dispatch) => {

        dispatch(CourseDopStarted());

        axios({
            method: 'post',
            url: 'api/Course/CreateCourse',
            data: course
        }).then(response => {
            console.log('Course is created.');

            dispatch(CreateCourseSuccess(response.data as CourseData));

            toast.success("Course is created successfully!", {
                position: toast.POSITION.TOP_CENTER
            });
        })
            .catch(error => {
                dispatch(CourseDopFailed(error))
            });
    }
}

Adding as any (dispatch(CreateCourse(course) as any) solves this issue but this is not a good practice in TS. I found some solutions but could not relate them with my own case. I appreciate any help!

2

Answers


  1. I think that because you used axios in the CreateCourse function and the axios function is of asynchronous type, your function is typed as a Promise. So try this:

    export function CreateCourse(course: CourseData) {
        return async (dispatch: Dispatch): Promise<void> => {
       // your code...
      }
    }
    
    Login or Signup to reply.
  2. The issue is that the core Dispatch type doesn’t know anything about thunks, just plain action objects.

    The best answer here is:

    • Stop using connect
    • Switch to using the modern React-Redux hooks API
    • Follow our guidelines for setting up a Redux store and inferring the correct type for dispatch from the store, and use a pre-typed version of the useSelector hook:

    https://redux.js.org/tutorials/typescript-quick-start

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search