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 :).
CodePudding user response:
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],
});
CodePudding user response:
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).