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()...
First time using this, so a nice explanation would be nice :).
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],
});