client/src/sagas/index.js
author ymh <ymh.work@gmail.com>
Tue, 20 Jun 2017 14:13:15 +0200
changeset 62 b2514a9bcd49
parent 59 1eb52770eefa
permissions -rw-r--r--
migrate to redux-offline + various optimisation

import { put, take, all } from 'redux-saga/effects'
import * as types from '../constants/actionTypes';

// ---

export function* watchLoginSubmit() {
  while (true) {
    const { username, password } = yield take(types.AUTH_LOGIN_SUBMIT);
    yield put({ type: types.AUTH_LOGIN_REQUEST, username, password });
  }
}

function* watchLoginRequest(context) {
  while (true) {
    try {

        const { username, password } = yield take(types.AUTH_LOGIN_REQUEST);
        const client = context.client;
        const response = yield client.post('/api/auth/login/', { username, password });

        const actions = [{
          type: types.AUTH_LOGIN_SUCCESS,
          user: response.user,
          token: response.token,
        //   meta: {
        //     transition: (prevState, nextState, action) => ({
        //       pathname: '/sessions',
        //     }),
        //   },
        }, {
          type: types.AUTH_STORE_TOKEN_ASYNC,
          token: response.token,
        }];

        yield all(actions.map(action => put(action)));
        context.history.push('/sessions');

    } catch(e) {
        yield put({ type: types.AUTH_LOGIN_ERROR, error: e });
    }
  }
}

function* watchStoreToken() {
  while (true) {
    const { token } = yield take(types.AUTH_STORE_TOKEN_ASYNC);
    yield put({ type: types.AUTH_STORE_TOKEN, token });
  }
}

function* watchUpdateSettings(context) {
  while (true) {
    const { username, firstname, lastname } = yield take(types.USER_UPDATE_SETTINGS_ASYNC);
    const client = context.client;
    try {
      yield client.put('/api/auth/user/', {
        username,
        first_name: firstname,
        last_name: lastname
      });
      yield put({ type: types.USER_UPDATE_SETTINGS, firstname, lastname });
    } catch (e) {

    }
  }
}

// ---

export default function* rootSaga(context) {
  yield all([
    watchLoginSubmit(),
    watchLoginRequest(context),
    watchStoreToken(),
    watchUpdateSettings(context),
  ])
}