{"size": 1179, "ext": "js", "max_stars_repo_path": "app/containers/SignInPage/saga.js", "max_stars_repo_name": "VisualizationLiteracyPlayground/vizblocks-www", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/containers/SignInPage/saga.js", "max_issues_repo_name": "VisualizationLiteracyPlayground/vizblocks-www", "max_issues_repo_issues_event_min_datetime": "2020-11-15T13:45:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-15T13:52:59.000Z", "max_forks_repo_path": "app/containers/SignInPage/saga.js", "max_forks_repo_name": "VisualizationLiteracyPlayground/vizblocks-www", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 2, "max_forks_count": null, "avg_line_length": 25.6304347826, "max_line_length": 69, "alphanum_fraction": 0.6242578456}
/* eslint-disable prefer-destructuring */
import { put, takeLatest } from 'redux-saga/effects';

import { post } from '../../utils/api';
import history from '../../utils/history';
import { userSignedIn, setSuccess } from '../App/actions';
import { userSignInFailure, userSignInSuccess } from './actions';
import { USER_SIGNIN } from './constants';

function* userSignIn({ email, password }) {
  const [success, response] = yield post(
    '/user/login',
    {
      email,
      password,
    },
    res => {
      localStorage.setItem('access_token', res.data['access-token']);
      return res;
    },
    e => e.response,
  );
  if (success) {
    yield put(userSignInSuccess());
    yield put(userSignedIn(response.data));
    yield put(
      setSuccess({
        title: 'Signed in!',
        description: '',
      }),
    );
    yield history.push('/my-stuff');
  } else {
    let msg = 'Unable to reach the server, please try again later.';
    if (response) {
      msg = response.data.error;
    }
    yield put(userSignInFailure(msg));
  }
}

// Individual exports for testing
export default function* signInPageSaga() {
  yield takeLatest(USER_SIGNIN, userSignIn);
}
