Skip to content

Instantly share code, notes, and snippets.

@seansean11
Last active January 25, 2023 19:03
Show Gist options
  • Save seansean11/196c436988c1fdf4b22cde308c492fe5 to your computer and use it in GitHub Desktop.
Save seansean11/196c436988c1fdf4b22cde308c492fe5 to your computer and use it in GitHub Desktop.
Using Redux Thunk with Typescript (example)
import { ActionCreator } from 'redux'
import { ThunkAction } from 'redux-thunk'
import { WebService } from 'app/services/WebService'
// Create this reusable type that can be imported into your redux action files
export type ThunkResult<R> = ThunkAction<R, RootState, Services, RootAction>
// Services are only necesarry because we are using
// `reduxThunk.withExtraArgument({ webService }))` when we are creating our store.
export type Services = {
webService: WebService
}
// Union type of all of your actions
export type RootAction = UserAction
// Interface of your root Redux state
export interface RootState {
readonly user: UserState
}
// Enum of your action types
export enum ActionType {
UserUpdate = 'USER_UPDATE',
}
export interface UserAction {
readonly type: ActionType
readonly user: Partial<UserState>
}
export interface UserState {
readonly groups: Array<string>
readonly isLoading: boolean
}
import {
Thunk,
ActionType,
UserAction,
UserState,
} from './storeTypes'
export const updateUser = (user: Partial<UserState>): UserAction => ({
type: ActionType.UserUpdate,
user
})
// ***** USING THUNKRESULT TYPE HERE ***** //
// this ThunkResult is `void` because it doesn't return anything
// if you return something from the thunk, replace `void` with the return value `ThunkResult<void>`
export const login = (email: string, password: string): ThunkResult<void> => async (
dispatch,
getState,
{ webService }
) => {
try {
const { jwt, groups } = await webService.signIn(
email,
password
)
webService.setBearerToken(jwt)
dispatch(updateUser({ groups }))
} catch (err) {
throw err
}
}
@n3rd253
Copy link

n3rd253 commented Apr 26, 2019 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment