In my slice, I have defined the action to be as follows: https://github.com/jasonabanico/RedGranite/blob/main/src/Client/RedGranite.Client.Web/src/app/containers/ItemPage/itemPageSlice.ts
export const addItem = createAsyncThunk(
'itemPage/addItem',
async (itemInput: ItemInput) => {
return await itemService
.addItem(itemInput)
.catch((err: any) => {
console.log("Error:", err);
});
},
)
I have also defined useAppDispatch as: https://github.com/jasonabanico/RedGranite/blob/main/src/Client/RedGranite.Client.Web/src/app/hooks.ts
export const useAppDispatch = () => useDispatch<AppDispatch>();
I use both of the above like so: https://github.com/jasonabanico/RedGranite/blob/main/src/Client/RedGranite.Client.Web/src/app/containers/ItemPage/addItemPage.tsx
const dispatch = useAppDispatch();
...
dispatch(addItem(itemInput));
I am getting the following error:
TS2345: Argument of type 'AsyncThunkAction<void | AddItem, ItemInput, AsyncThunkConfig>' is not assignable to parameter of type 'AnyAction'. 21 | longDescription 22 | };
23 | dispatch(addItem(itemInput)); | ^^^^^^^^^^^^^^^^^^ 24 | };
What is wrong with my definitions? Why can't I use addItem in dispatch?
UPDATE:
Code in repo updated to this, but getting same error.
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();
UPDATE:
To replicate in Codesandbox.
I finally found the the reason.
That was because you defined middleware separately with any
type in store.ts
.
So I fixed your issue by adjusting your store.ts
file like this:
import {
configureStore,
ThunkAction,
Action
} from "@reduxjs/toolkit";
import homePageReducer from "./containers/HomePage/homePageSlice";
import itemPageReducer from "./containers/ItemPage/itemPageSlice";
import ReduxLogger from "redux-logger";
export const store = configureStore({
middleware:(getDefaultMiddleware) =>
getDefaultMiddleware().concat(ReduxLogger),
reducer: {
homePage: homePageReducer,
itemPage: itemPageReducer,
},
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>;
The type of AppDispatch
should be ThunkDispatch<any, undefined, UnknownAction> & Dispatch<UnknownAction>
, but it was just Dispatch<UnknownAction>
. So it didn't work. It's due to type of getDefaultMiddleware
was any
.