Skip to content

Instantly share code, notes, and snippets.

@kuy
Created April 24, 2016 16:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuy/18aca23ac885d36eeb5f687a9ad7eff1 to your computer and use it in GitHub Desktop.
Save kuy/18aca23ac885d36eeb5f687a9ad7eff1 to your computer and use it in GitHub Desktop.
redux-sagaを使ったとてもシンプルな認証処理
import { push } from 'react-router-redux';
function* authSaga() {
while (true) {
// ログインするまでずっと待つ
const { user, pass } = yield take(REQUEST_LOGIN);
// 認証処理の呼び出し(ここではtry-catchを使わず戻り値にエラー情報が含まれるスタイル)
let { token, error } = yield call(authorize, user, pass);
if (!token && error) {
yield put({ type: FAILURE_LOGIN, payload: error });
continue; // 認証に失敗したらリトライに備えて最初に戻る
}
// ログイン成功の処理(トークンの保存など)
yield put({ type: SUCCESS_LOGIN, payload: token });
// ログアウトするまでずっと待つ
yield take(REQUEST_LOGOUT);
// ログアウト処理(トークンのクリアなど)
yield call(SUCCESS_LOGOUT);
}
}
function* pageSaga() {
while (true) {
// ログイン成功するまでずっと待つ
yield take(SUCCESS_LOGIN);
// ダッシュボードページに移動する
yield put(push('/dashboard'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment