Last active
April 23, 2020 12:31
-
-
Save pie6k/8d67429bf5ca4bb729108aa91c9a2a50 to your computer and use it in GitHub Desktop.
Better way to create type-safe Redux actions and reducers with Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface LoginData { | |
email: string; | |
password: string; | |
} | |
export interface UserData { | |
id: string; | |
email: string; | |
profilePicture: string; | |
} | |
export type LoginAction = | |
| { type: 'LOGIN_REQUEST'; input: LoginData } | |
| { type: 'LOGIN_SUCCESS'; user: UserData } | |
| { type: 'LOGIN_FAILED'; error: string }; | |
// action creators | |
export function loginRequest(input: LoginData): LoginAction { | |
return { type: 'LOGIN_REQUEST', input }; | |
} | |
export function loginSuccess(user: UserData): LoginAction { | |
return { type: 'LOGIN_SUCCESS', user }; | |
} | |
export function loginFailed(error: string): LoginAction { | |
return { type: 'LOGIN_FAILED', error }; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { LoginAction, UserData } from './actions'; | |
interface LoginState { | |
user: UserData; | |
isLoading: boolean; | |
error: string; | |
} | |
const initialState: LoginState = { | |
user: null, | |
error: null, | |
isLoading: false | |
} | |
export function loginReducer(state = initialState, action: LoginAction): LoginState { | |
switch (action.type) { | |
case 'LOGIN_REQUEST': | |
return {...state, isLoading: true} | |
case 'LOGIN_SUCCESS': | |
return {...state, isLoading: false, user: action.user} | |
case 'LOGIN_FAILED': | |
return {...state, isLoading: false, error: action.error} | |
default: | |
return state; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment