Reputation: 2304
I have set up a redux thunk function with typescript like this:
export const fetchActivities = (): AppThunk => async dispatch => {
dispatch(fetchActivitiesRequest())
try {
const res = await fetch("/activities")
const body = await res.json()
dispatch(fetchActivitiesSuccess(body))
} catch (err) {
dispatch(fetchActivitiesError(err))
}
}
AppThunk is simply a type deriving from the ThunkAction type, with the following type params:
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, {}, null, Action<string>>
My issue is, that when i try to setup a unit test for my action, and when I try to dispatch the thunk action like this:
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore({ activities: [] })
store.dispatch(actions.fetchActivities())
I receive the following error message:
Argument of type 'ThunkAction<void, {}, null, Action<string>>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type 'ThunkAction<void, {}, null, Action<string>>' but required in type 'AnyAction'.ts(2345)
I have tried searching around for a solution to this issue, though without success. Most suggestions say to try and add an any param to the generic for dispatch, so dispatch<any>(actions.fetchActivities())
. While this works to stop the typing error, only the first action in the thunk will get dispatched, while everything within the try and catch statements are ignored.
Does anyone have any suggestions as to how to fix this issue?
Upvotes: 29
Views: 37514
Reputation: 1060
if you are using hooks, you can add the type "any" to the hook
const dispatch = useDispatch<any>()
Upvotes: 8
Reputation: 1
Change middlewares = [thunk] to middlewares = getDefaultMiddleware => getDefaultMiddleware()
Upvotes: -1
Reputation: 44136
These are two distinct problems. Typings of any way will never influence runtime behaviour.
Firstly: So your thunk not firing any other action can only have one meaning: The other calls to dispatch
are most likely never reached.
Are you sure your call to fetch
ever terminates? It might just wait forever for an answer or something like that.
Secondly, your typing problem: The normal Dispatch
type just does not support thunks per default. Your solution with Dispatch<any>
is okay. Otherwise, you could cast your dispatch
function to ThunkDispatch
from the redux-thunk
package.
Edit: Sorry, this just looked exactly like the RTK error, but it is something different. (Original, possibly wrong answer)
This is a known bug in RTK with a currently open PR that would fix it - I didn't get around to finalize it since I'm sick at the moment, but you can use the CI build until we put out a new version. You can install it via
yarn add https://pkg.csb.dev/reduxjs/redux-toolkit/commit/933aa4a1/@reduxjs/toolkit
or
npm i https://pkg.csb.dev/reduxjs/redux-toolkit/commit/933aa4a1/@reduxjs/toolkit
Upvotes: 15