Last active
April 29, 2019 22:26
-
-
Save hedgerh/d47e4e33f2e6882fb663109a6d061c96 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { 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