Skip to content

Instantly share code, notes, and snippets.

@hedgerh
Last active April 29, 2019 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hedgerh/d47e4e33f2e6882fb663109a6d061c96 to your computer and use it in GitHub Desktop.
Save hedgerh/d47e4e33f2e6882fb663109a6d061c96 to your computer and use it in GitHub Desktop.
import { call, put, takeLatest } from 'redux-saga/effects'
import { createStandardAction, ActionType, getType } from 'typesafe-actions'
import client from '../httpClient'
interface ILogin {
email: string;
password: string;
}
interface IUser {
id: number;
username: string;
}
const http = {
login: (credentials: ILogin) => client.post('/login', credentials),
}
const actions = {
login: createStandardAction('LOGIN')<ILogin>(),
loginSuccess: createStandardAction('LOGIN_SUCCESS')<IUser>(),
loginError: createStandardAction('LOGIN_ERROR')<string>(),
}
function* loginSaga(action: ActionType<typeof actions.login>) {
try {
const user: IUser = yield call(http.login, action.payload)
yield put(actions.loginSuccess(user))
} catch (e) {
yield put(actions.loginError('Uh oh'))
}
}
export function* authSagas() {
yield takeLatest(getType(actions.login), loginSaga)
}
interface IState {
isLoading: boolean;
user?: IUser;
}
const initialState: IState = {
isLoading: false,
}
type Action = ActionType<typeof actions>
export default function reducer(state: IState, action: Action) {
switch (action.type) {
case getType(actions.login):
return { ...state, isLoading: true }
case getType(actions.loginSuccess):
return { ...state, user: action.payload }
case getType(actions.loginError):
return { ...state, isLoading: false }
}
return state
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment