New to typescript + redux ecosystem here.
How do I properly encapsulate type information into async actions when using redux-actions, redux-thunk and redux-promise-middleware in TypeScript?
An example of authentication:
/* actions */
const login = createAction(LOGIN, authService.login);
/* authService */
async function login(payload: LoginPayload): Promise<LoginResponse> {
// ... authenticate here.
}
Since I'm using redux-promise-middleware, the actions LOGIN_PENDING
, LOGIN_FULFILLED
/LOGIN_REJECTED
are dispatched automatically. How do I create types for these such that the reducer can figure out what action object it's dealing with?
Since redux-actions follows FSA, _FULFILLED
should have action.payload
. _REJECTED
should have action.error
/* reducer */
function loginReducer(state: AppState, action: AuthAction) {
switch (action.type) {
case LOGIN_FULFILLED:
// action.payload should be defined as LoginResponse object here.
// action.error shouldnt be present.
case LOGIN_REJECTED:
// action.error should be defined
}
}
How would I go about creating the AuthAction
type? I'm guessing it should be a union type of each of the individual action types (which can be union types on their own). redux-actions
also provides Action
and BaseAction
types for this.