I'm using redux-tookit for state.
My action:
const updateSomething = (data: string) => async (dispatch) => {
await user.set({ data })
dispatch(updatedData(data))
}
In my view I want to do something like:
const dispatch = useDispatch()
await dispatch(updateSomething('Hi!'))
If typeof store.dispatch
still doesn't give you the right typing with ThunkDispatch
as one of the overloaded options, you may consider manually typing it, like so: -
export type AppDispatch = ThunkDispatch<AppState, null | undefined, AnyAction> &
Dispatch<AnyAction>;
Note: This is the correct typing with the default middleware, if you have added more middlewares you should try to figure out the possibilities.
While my proposed solution (below) works in codesandbox, it doesn't work in my project, which I ported from vanilla redux to redux toolkit. Maybe some of the packages installed break the types, just a speculation but when I include redux-debounced
in my codesandbox sample (link below), the type for store.dispatch
is falled back to Dispatch<AnyAction>
, even without including redux-debounced
in middleware.
This is certainly a mystery that has to be resolved!!
I had the similar issue as TS, so I made a simple project in codesandbox and surprisingly it works with a minor tweak!
In my view, what TS meant is that updateSomething('Hi!')
is a valid thunk created using createAsyncThunk()
in redux toolkit, where dispatching the thunk should return a Promise
. That's a feature in redux toolkit. But unfortunately, somehow typescript is returning AsyncThunkAction
and invoking the following line:
await dispatch(updateSomething('Hi!'));
actually yields a typing error. Here's what I got in my codesandbox project:
In my case, fetchDynamicName()
is a valid thunk and supposedly the type of dispatchReturn
should be a Promise
.
With a minor tweak found in this post , it actually works!!
All we need is to export the dispatch type of the store, like so:
export type AppDispatch = typeof store.dispatch;
and assign the type to the dispatch function before using it:
const dispatch: AppDispath = useDispatch();
And voilà: See the screenshot below:
You can take a look at my codesandbox project at https://codesandbox.io/s/fast-cdn-08vpu?file=/src/App.tsx .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.