Skip to content

Instantly share code, notes, and snippets.

@pie6k
Last active April 23, 2020 12:31
Show Gist options
  • Save pie6k/8d67429bf5ca4bb729108aa91c9a2a50 to your computer and use it in GitHub Desktop.
Save pie6k/8d67429bf5ca4bb729108aa91c9a2a50 to your computer and use it in GitHub Desktop.
Better way to create type-safe Redux actions and reducers with Typescript
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 };
}
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