Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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