{"size": 1902, "ext": "js", "max_stars_repo_path": "login-react/react-login-front-end-app/app/containers/AuthPage/saga.js", "max_stars_repo_name": "rama5789/strapi-examples", "max_stars_repo_stars_event_min_datetime": "2020-03-22T11:33:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-22T11:33:21.000Z", "max_issues_repo_path": "login-react/react-login-front-end-app/app/containers/AuthPage/saga.js", "max_issues_repo_name": "doc22940/strapi-examples", "max_issues_repo_issues_event_min_datetime": "2021-03-02T01:02:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T12:19:14.000Z", "max_forks_repo_path": "login-react/react-login-front-end-app/app/containers/AuthPage/saga.js", "max_forks_repo_name": "devcodedao/Ex-react", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": 11, "max_forks_count": null, "avg_line_length": 28.8181818182, "max_line_length": 87, "alphanum_fraction": 0.6550998948}
import { LOCATION_CHANGE } from 'react-router-redux';
import { all, call, fork, takeLatest, select, take, cancel } from 'redux-saga/effects';
import { set } from 'lodash';
import { history } from 'app';

// Utils
import auth from 'utils/auth';
import request from 'utils/request';

import { makeSelectFormType, makeSelectModifiedData } from './selectors';
import { SUBMIT } from './constants';

export function* submitForm() {
  try {
    const formType = yield select(makeSelectFormType());
    const body = yield select(makeSelectModifiedData());
    let requestURL;

    switch (formType) {
      case 'login':
        requestURL = 'http://localhost:1337/auth/local';
        break;
      case 'register':
        requestURL = 'http://localhost:1337/auth/local/register';
        break;
      case 'reset-password':
        requestURL = 'http://localhost:1337/auth/reset-password';
        break;
      case 'forgot-password':
        requestURL = 'http://localhost:1337/auth/forgot-password';
        set(body, 'url', 'http://localhost:3000/auth/reset-password');
        break;
      default:

    }

    const response = yield call(request, requestURL, { method: 'POST', body });

    if (response.jwt) {
      // Set the user's credentials
      yield all([
        call(auth.setToken, response.jwt, body.rememberMe),
        call(auth.setUserInfo, response.user, body.rememberMe),
      ]);
      yield call(forwardTo, '/');
      const submitWatcher = yield fork(takeLatest, SUBMIT, submitForm);
      yield cancel(submitWatcher);
    }
  } catch(error) {
    console.log(error.response.payload.message);
  }
}

export default function* defaultSaga() {
  yield fork(takeLatest, SUBMIT, submitForm);
  yield take(LOCATION_CHANGE);
}

/**
 * Helper to handle navigation from sagas.
 * @param  {String} location The path to navigate
 */
function forwardTo(location) {
  history.push(location);
}
