2.註冊-React部分

註冊部分相對於登入只是將email,password送出到server,server確認無誤後存進資料庫,蠻單純的。

export function signUp(data) {
  return dispatch => {
    dispatch({
      type: types.SIGNUP_USER
    });

    return fetchHelper('post', '/api/signup', data)
      .then((result) => {
        dispatch(signUpSuccess(result));
      }).catch((err) => {
        parseJSON(err).then(error => {
          dispatch({
            type: types.SIGNUP_ERROR_USER,
            error: error
          });
        });
      });
  };
}

function signUpSuccess(obj) {
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
    localStorage.setItem('token', obj.token);
  }
  return {
    type: types.SIGNUP_SUCCESS_USER,
    user: obj.user
  };
}

其他大致上等同於登入作業,附上reducer片段

export default function user(state={
  isWaiting: false,
  authenticated: false,
  error: null,
  favoriteRecipes: null }, action={}) {
  switch (action.type) {
    case SIGNUP_USER:
      return Object.assign({}, state, {
        isWaiting: true
      });
    case SIGNUP_SUCCESS_USER:
      return Object.assign({}, state, {
        isWaiting: false,
        authenticated: true,
        user: action.user
      });
    case SIGNUP_ERROR_USER:
      return Object.assign({}, state, {
        isWaiting: false,
        authenticated: false,
        error: action.error
      });
    default:
      return state;
  }
}