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
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:
The issue is that the core
Dispatch
type doesn’t know anything about thunks, just plain action objects.The best answer here is:
connect
dispatch
from the store, and use a pre-typed version of theuseSelector
hook:https://redux.js.org/tutorials/typescript-quick-start