I'm using redux-thunk
to use async action creators. The result is also returned to the respective caller.
function fetchUserName(userId: number): Promise<string> {
return Promise.resolve(`User ${userId}`)
}
function requestUserName(userId: number) {
return (dispatch: Dispatch) => {
return fetchUserName(userId).then(name => {
dispatch({
type: 'SET_USERNAME',
payload: name,
})
})
}
}
This way, the store is updated, while allowing the components to handle the response directly.
function User() {
const dispatch = useDispatch()
useEffect(() => {
dispatch(requestUserName(1))
.then(name => {
console.log(`user name is ${name}`)
})
.catch(reason => {
alert('failed fetching user name')
})
}, [])
}
This is working as intended, but it will not be compiled by TypeScript due to invalid types.
- The
dispatch
returned byuseDispatch
is not recognized as a function that returns a Promise and so TypeScript argues thatProperty 'then' does not exist on type '(dispatch: Dispatch<AnyAction>) => Promise<void>'.
. - Even if it would be recognized so, the Promise should be correctly typed
How can this situation be solved?
It would be perfectly fine for me to create a wrapper around useDispatch
or to redefine the type of dispatch
but I have no idea how that type should look like in this particular situation.
Thank you very much for any suggestion.