'Argument of type 'AsyncThunkAction<any, void, {}>' is not assignable to parameter of type 'AnyAction'
store.ts
export const store = configureStore({
reducer: {
auth: authReducer
},
middleware: [],
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
hooks.ts
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
authSlice.ts (function that causes the problem)
export const fetchUser = createAsyncThunk(
'users/fetchByTok',
async () => {
const res = await getUser();
return res.data;
}
)
Auth.ts
const Auth = ({ component, isLogged }: {component: any, isLogged: boolean}) => {
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(fetchUser()) // <----------- ERROR
}, []);
return isLogged ? component : <Navigate to='/sign-in' replace={true} />;
}
export default Auth;
I have a createAsyncThunk function that fetches the user, but I cannot actually put it in the dispatch()...
- Argument of type 'AsyncThunkAction<any, void, {}>' is not assignable to parameter of type 'AnyAction'.
- Property 'type' is missing in type 'AsyncThunkAction<any, void, {}>' but required in type 'AnyAction'.ts(2345)
First time using this, so a nice explanation would be nice :).
Solution 1:[1]
EDIT!
Since as mentioned in the comment, redux toolkit actually adds Thunk by default, the answer from Phry is more accurate. I can't delete the accepted answer, so this edit would have to suffice.
The answer that I provided will remove other middlewares that are automatically added!
The problem is that you're actually missing the thunk middleware inside store configuration. Just add an import for thunkMiddleware
and add it in the middleware
array in your configuration. Since the middleware is not added, the dispatch won't accept the Thunk Action, because it is not supported by redux out of a box.
import thunkMiddleware from 'redux-thunk';
export const store = configureStore({
reducer: {
auth: authReducer
},
middleware: [thunkMiddleware],
});
Solution 2:[2]
I faced the same issue, for me it was just solved by adding AppDispatch
to the type of useDispatch
hook;
const dispatch = useDispatch<AppDispatch>();
useEffect(() => {
dispatch(getUsers());
}, []);
getUsers() was my createAsyncThunk
function
Solution 3:[3]
There is a common TS issue that surfaces like this if you have redux
in the versions 4.0.5 and 4.1.x both somewhere in your node_modules
.
For many people, uninstalling and re-installing react-redux
or @types/react-redux
seems to solve the problem.
Otherwise your bundler might help you find the source of that problem (npm ls redux
or yarn why redux
if you are using one of those two).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | wasilikoslow |
Solution 3 | phry |